import { useState, useEffect, useCallback } from "react";
import { Control, FieldErrors, Controller, UseFormWatch, UseFormSetValue } from "react-hook-form";
import { FirstTimeHomeBuyerFormData } from "../schema";
import { uploadFTHBDocument, getFTHBApplicationDocuments, getDocumentsByService } from "@/src/services/web/services";
import Link from "next/link";
import { InfoIcon } from "lucide-react";

interface Step5Props {
  control: Control<FirstTimeHomeBuyerFormData>;
  errors: FieldErrors<FirstTimeHomeBuyerFormData>;
  isReadOnly: boolean;
  watch: UseFormWatch<FirstTimeHomeBuyerFormData>;
  setValue: any;
  applicationId: number | null;
  setError: any;
  clearErrors: any;
  trigger: any;
  onValidate?: (validateFn: () => boolean) => void;
}

interface DocumentType {
  id: number;
  document_name: string;
  is_required: number;
  info?: string;
  upload_type?: string;
}

export default function Step5({ control, errors, isReadOnly, watch, setValue, applicationId, setError, clearErrors, trigger, onValidate }: Step5Props) {
  const [files, setFiles] = useState<Record<number, File[]>>({});
  const [savedDocuments, setSavedDocuments] = useState<Record<string, any>>({});
  const [fileErrors, setFileErrors] = useState<Record<number, string>>({});
  const [documentList, setDocumentList] = useState<DocumentType[]>([]);
  const [loading, setLoading] = useState(true);
  const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});

  useEffect(() => {
    loadDocumentMaster();
  }, []);

  useEffect(() => {
    if (applicationId && documentList.length > 0) {
      loadSavedDocuments();
    }
  }, [applicationId, documentList]);

  const loadDocumentMaster = async () => {
    try {
      const response = await getDocumentsByService("First Time Home Buyer Program");
      if (response.data.success) {
        setDocumentList(response.data.data);
      }
    } catch (error) {
      console.error('Error loading document master:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadSavedDocuments = async () => {
    if (!applicationId) return;
    try {
      const response = await getFTHBApplicationDocuments(applicationId);
      const docs = response.data.data;
      const docMap: Record<string, any[]> = {};
      
      // Group documents by document_type
      docs.forEach((doc: any) => {
        if (!docMap[doc.document_type]) {
          docMap[doc.document_type] = [];
        }
        docMap[doc.document_type].push(doc);
      });
      
      setSavedDocuments(docMap);
      
      // Update form validation state for existing documents
      documentList.forEach((docType) => {
        const fieldName = generateFieldName(docType.document_name);
        if (docMap[docType.document_name] && docMap[docType.document_name].length > 0) {
          setValue(`documents.${fieldName}`, true);
        }
      });
    } catch (error) {
      console.error('Error loading documents:', error);
    }
  };

  const generateFieldName = (documentName: string): string => {
    return documentName
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '')
      .replace(/^(.{20}).*$/, '$1');
  };

  const validateRequiredDocuments = useCallback(() => {
    let hasErrors = false;
    const newErrors: Record<string, string> = {};

    documentList.forEach((doc) => {
      if (doc.is_required === 1) {
        const hasSavedDoc = savedDocuments[doc.document_name] && savedDocuments[doc.document_name].length > 0;
        if (!hasSavedDoc) {
          newErrors[doc.document_name] = `This document is required`;
          hasErrors = true;
        }
      }
    });

    setValidationErrors(newErrors);
    return !hasErrors;
  }, [documentList, savedDocuments]);

  // Pass validation function to parent
  useEffect(() => {
    if (onValidate) {
      onValidate(validateRequiredDocuments);
    }
  }, [validateRequiredDocuments, onValidate]);

  const handleFileChange = async (index: number, newFiles: FileList | null) => {
    if (!newFiles || newFiles.length === 0) return;
    if (!applicationId) {
      setFileErrors((prev) => ({ ...prev, [index]: 'Application ID not available' }));
      return;
    }
    
    const doc = documentList[index];
    const isMultiple = doc.upload_type === "multiple";
    const filesToUpload = isMultiple ? Array.from(newFiles) : [newFiles[0]];

    // Validate file sizes
    for (const file of filesToUpload) {
      if (file.size > 5 * 1024 * 1024) {
        setFileErrors((prev) => ({ ...prev, [index]: 'File size exceeds 5MB limit' }));
        return;
      }
    }
    
    try {
      // Upload files one by one
      for (const file of filesToUpload) {
        const formData = new FormData();
        formData.append('document', file);
        formData.append('documentType', doc.document_name);
        formData.append('applicationId', applicationId.toString());
        
        const response = await uploadFTHBDocument(formData);
        
        if (!response.data.success) {
          throw new Error('Upload failed');
        }
      }
      
      setFiles((prev) => ({ ...prev, [index]: [...(prev[index] || []), ...filesToUpload] }));
      setFileErrors((prev) => {
        const copy = { ...prev };
        delete copy[index];
        return copy;
      });
      
      // Clear validation error for this document
      setValidationErrors((prev) => {
        const copy = { ...prev };
        delete copy[doc.document_name];
        return copy;
      });
      
      // Update form validation state
      const fieldName = generateFieldName(doc.document_name);
      setValue(`documents.${fieldName}`, true);
      
      await loadSavedDocuments();
    } catch (error) {
      console.error('Upload error:', error);
      setFileErrors((prev) => ({ ...prev, [index]: 'Failed to upload file' }));
    }
  };

  const removeFile = (index: number, fileIndex: number) => {
    setFiles((prev) => {
      const updated = { ...prev };
      updated[index] = updated[index]?.filter((_, i) => i !== fileIndex) || [];
      return updated;
    });
  };

  return (
    <div>
      <h2 className="text-lg font-semibold mb-8 text-center text-gray-800">
        DOCUMENT SUMMARY
      </h2>

      {loading ? (
        <div className="text-center py-8 text-gray-500">Loading documents...</div>
      ) : (
        <div className="space-y-4">
          {documentList.map((doc, index) => {
            const hasFiles = files[index] && files[index].length > 0;
            const savedDocs = savedDocuments[doc.document_name] || [];
            const hasDocument = hasFiles || savedDocs.length > 0;
            const fieldName = generateFieldName(doc.document_name);
            const isMultiple = doc.upload_type === "multiple";

            return (
              <div
                key={doc.id}
                className="border border-gray-100 rounded-lg p-4 flex flex-col md:flex-row md:items-start md:justify-between gap-4 bg-gray-50/50"
              >
                {/* Document Info */}
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <p className="text-sm font-medium text-gray-700">
                      {index + 1}. {doc.document_name}
                    </p>
                    {doc.is_required === 1 && !isReadOnly && <span className="text-red-500 text-xs">*</span>}
                    {doc.info && (
                      <div className="relative group inline-block">
                        <InfoIcon className="w-4 h-4 text-blue-400 hover:text-blue-600 cursor-pointer" />
                        <div className="absolute left-1/2 -translate-x-1/2 bottom-full mb-2 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 pointer-events-none z-50 min-w-30">
                          <div className="bg-teal-900/20  text-[#323232]  text-xs rounded-lg shadow-lg py-2 px-3">
                            {doc.info}
                            <div className="absolute left-1/2 -translate-x-1/2 top-full -mt-1">
                              <div className="w-0 h-0 border-l-4 border-r-4 border-t-4 border-l-transparent border-r-transparent border-t-gray-900"></div>
                            </div>
                          </div>
                        </div>
                      </div>
                    )}
                    {isMultiple && (
                      <span className="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full font-medium">
                        Multiple
                      </span>
                    )}
                  </div>

                  {/* Show uploaded documents */}
                  {savedDocs.length > 0 && (
                    <div className="mt-2 space-y-1">
                      {savedDocs.map((savedDoc: any, docIndex: number) => (
                        <div key={docIndex} className="flex items-center gap-2">
                          <svg className="w-3 h-3 text-teal-600" fill="currentColor" viewBox="0 0 20 20">
                            <path
                              fillRule="evenodd"
                              d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                              clipRule="evenodd"
                            />
                          </svg>
                          <p className="text-xs text-teal-600">
                            {savedDoc.original_name || "Document uploaded"}
                          </p>
                          {/* {!isReadOnly && ( */}
                            <Link
                              target="_blank"
                              href={`${process.env.NEXT_PUBLIC_EXPRESS_BACKEND_PUBLIC}/documents/${savedDoc.file_name}`}
                              className="text-xs text-teal-600 hover:text-teal-700 underline"
                            >
                              View
                            </Link>
                          {/* )} */}
                        </div>
                      ))}
                    </div>
                  )}

                  {/* Show newly selected files */}
                  {hasFiles && (
                    <div className="mt-2 space-y-1">
                      {files[index].map((file, fileIndex) => (
                        <div key={fileIndex} className="flex items-center gap-2">
                          <span className="text-xs text-gray-600">{file.name}</span>
                          {!isReadOnly && (
                            <button
                              type="button"
                              onClick={() => removeFile(index, fileIndex)}
                              className="text-red-500 hover:text-red-700 text-xs font-medium"
                            >
                              ×
                            </button>
                          )}
                        </div>
                      ))}
                    </div>
                  )}

                  {!hasDocument && (
                    <>
                      <p className="text-xs text-gray-400 italic mt-1">
                        Not uploaded yet.
                      </p>
                      {validationErrors[doc.document_name] && (
                        <p className="text-xs text-red-500 mt-2 bg-red-50 p-2 rounded border border-red-100">
                          {validationErrors[doc.document_name]}
                        </p>
                      )}
                    </>
                  )}
                </div>

                {/* Upload/View Action */}
                <div className="flex items-center gap-3">
                  {!isReadOnly ? (
                    <>
                      <label className="px-4 py-1.5 bg-teal-600 text-white text-xs font-semibold rounded hover:bg-teal-700 cursor-pointer transition-colors shadow-sm">
                        {hasDocument ? "Add More" : "Upload"}
                        <input
                          type="file"
                          className="hidden"
                          multiple={isMultiple}
                          onChange={(e) => handleFileChange(index, e.target.files)}
                        />
                      </label>
                    </>
                  ) : savedDocs.length > 0 ? (
                    <span className="text-xs text-gray-600">
                      {savedDocs.length} file(s) uploaded
                    </span>
                  ) : (
                    <span className="text-xs font-medium text-gray-400 uppercase tracking-wider px-3 py-1 bg-gray-100 rounded">
                      Pending
                    </span>
                  )}
                </div>

                {fileErrors[index] && !isReadOnly && (
                  <p className="text-xs text-red-500 mt-2 bg-red-50 p-2 rounded border border-red-100">
                    {fileErrors[index]}
                  </p>
                )}
              </div>
            );
          })}
        </div>
      )}

{Object.keys(validationErrors).length > 0 && !isReadOnly && (
          <div className="mt-6 p-4 bg-red-50 border border-red-200 rounded-lg">
            <h4 className="text-red-800 text-sm font-semibold mb-2">Missing Required Documents:</h4>
            <ul className="text-red-700 text-xs list-disc list-inside space-y-1">
              {Object.entries(validationErrors).map(([docName, error]) => (
                <li key={docName}>{docName}: {error}</li>
              ))}
            </ul>
          </div>
        )}
    </div>
  );
}