import { useState, useRef } from 'react';
import { getDocumentPreviewUrl } from '@/services/workflowApi';
import { toast } from 'sonner';

export interface DocumentPolicy {
  maxFileSizeMB: number;
  allowedFileTypes: string[];
}

export interface PreviewDocument {
  fileName: string;
  fileType: string;
  fileUrl: string;
  fileSize?: number;
  file?: File;
  documentId?: string;
}

/**
 * Custom Hook: useDocumentManagement
 * 
 * Purpose: Manages document upload, validation, and preview
 * 
 * Responsibilities:
 * - Validates files against policy
 * - Manages document lists (new and existing)
 * - Handles document deletion
 * - Manages document preview
 */
export function useDocumentManagement(
  documentPolicy: DocumentPolicy,
  _isEditing: boolean = false
) {
  const [documents, setDocuments] = useState<File[]>([]);
  const [existingDocuments, setExistingDocuments] = useState<any[]>([]);
  const [documentsToDelete, setDocumentsToDelete] = useState<string[]>([]);
  const [previewDocument, setPreviewDocument] = useState<PreviewDocument | null>(null);
  const [documentErrorModal, setDocumentErrorModal] = useState<{
    open: boolean;
    errors: Array<{ fileName: string; reason: string }>;
  }>({
    open: false,
    errors: []
  });
  const fileInputRef = useRef<HTMLInputElement>(null);

  const validateFile = (file: File): { valid: boolean; reason?: string } => {
    const maxSizeBytes = documentPolicy.maxFileSizeMB * 1024 * 1024;
    if (file.size > maxSizeBytes) {
      return {
        valid: false,
        reason: `File size exceeds the maximum allowed size of ${documentPolicy.maxFileSizeMB}MB. Current size: ${(file.size / (1024 * 1024)).toFixed(2)}MB`
      };
    }

    const fileName = file.name.toLowerCase();
    const fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);

    if (!documentPolicy.allowedFileTypes.includes(fileExtension)) {
      return {
        valid: false,
        reason: `File type "${fileExtension}" is not allowed. Allowed types: ${documentPolicy.allowedFileTypes.join(', ')}`
      };
    }

    return { valid: true };
  };

  const handleFileUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(event.target.files || []);

    if (files.length === 0) return;

    const validationErrors: Array<{ fileName: string; reason: string }> = [];
    const validFiles: File[] = [];

    files.forEach(file => {
      const validation = validateFile(file);
      if (!validation.valid) {
        validationErrors.push({
          fileName: file.name,
          reason: validation.reason || 'Unknown validation error'
        });
      } else {
        validFiles.push(file);
      }
    });

    if (validationErrors.length > 0) {
      setDocumentErrorModal({
        open: true,
        errors: validationErrors
      });
    }

    if (validFiles.length > 0) {
      setDocuments(prev => [...prev, ...validFiles]);
      if (validFiles.length < files.length) {
        toast.warning(`${validFiles.length} of ${files.length} file(s) were added. ${validationErrors.length} file(s) were rejected.`);
      } else {
        toast.success(`${validFiles.length} file(s) added successfully`);
      }
    }

    if (event.target) {
      event.target.value = '';
    }
  };

  const removeDocument = (index: number) => {
    setDocuments(prev => prev.filter((_, i) => i !== index));
  };

  const markDocumentForDeletion = (documentId: string) => {
    setDocumentsToDelete(prev => [...prev, documentId]);
  };

  const unmarkDocumentForDeletion = (documentId: string) => {
    setDocumentsToDelete(prev => prev.filter(id => id !== documentId));
  };

  const openPreview = (doc: any, isExisting: boolean = false) => {
    if (isExisting) {
      const docId = doc.documentId || doc.document_id || '';
      setPreviewDocument({
        fileName: doc.originalFileName || doc.fileName || 'Document',
        fileType: doc.fileType || doc.file_type || 'application/octet-stream',
        fileUrl: getDocumentPreviewUrl(docId),
        fileSize: Number(doc.fileSize || doc.file_size || 0),
        documentId: docId
      });
    } else {
      const fileUrl = URL.createObjectURL(doc);
      setPreviewDocument({
        fileName: doc.name,
        fileType: doc.type || 'application/octet-stream',
        fileUrl: fileUrl,
        fileSize: doc.size,
        file: doc
      });
    }
  };

  const closePreview = () => {
    if (previewDocument?.fileUrl && previewDocument?.file) {
      URL.revokeObjectURL(previewDocument.fileUrl);
    }
    setPreviewDocument(null);
  };

  const canPreview = (doc: any, isExisting: boolean = false): boolean => {
    if (isExisting) {
      const type = (doc.fileType || doc.file_type || '').toLowerCase();
      const name = (doc.originalFileName || doc.fileName || '').toLowerCase();
      return type.includes('image') || type.includes('pdf') ||
             name.endsWith('.jpg') || name.endsWith('.jpeg') ||
             name.endsWith('.png') || name.endsWith('.gif') ||
             name.endsWith('.pdf');
    } else {
      const type = (doc.type || '').toLowerCase();
      const name = (doc.name || '').toLowerCase();
      return type.includes('image') || type.includes('pdf') ||
             name.endsWith('.jpg') || name.endsWith('.jpeg') ||
             name.endsWith('.png') || name.endsWith('.gif') ||
             name.endsWith('.pdf');
    }
  };

  return {
    documents,
    setDocuments,
    existingDocuments,
    setExistingDocuments,
    documentsToDelete,
    setDocumentsToDelete,
    previewDocument,
    documentErrorModal,
    setDocumentErrorModal,
    fileInputRef,
    handleFileUpload,
    removeDocument,
    markDocumentForDeletion,
    unmarkDocumentForDeletion,
    openPreview,
    closePreview,
    canPreview
  };
}

