"use client";

import { useEffect, useState } from "react";
import { PDFViewer, pdf } from "@react-pdf/renderer";
import type { ReactElement } from "react";
import type { DocumentProps } from "@react-pdf/renderer";
import { documentService } from "@/src/services/documentService";
import TabButton from "./pdf-preview/TabButton";
import UploadedDocumentsTab from "./pdf-preview/UploadedDocumentsTab";
import AttachmentsTab from "./pdf-preview/AttachmentsTab";
import CertificatesTab from "./pdf-preview/CertificatesTab";
import { usePDFDocuments } from "./pdf-preview/usePDFDocuments";
import { getAgreementUrl, getDocumentUrl, getQuotationUrl, getSiteVisitUrl, getMaintenancePhotoUrl, getSafeFilename, addFileToZip } from "@/src/lib/admin/utils";
import JSZip from "jszip";
import Button from "../admin/ui/button/Button";


interface PDFPreviewModalProps {
  isOpen: boolean;
  onClose: () => void;
  onDownload: () => void;
  pdfDocument: ReactElement<DocumentProps>;
  title: string;
  applicationId: number;
  applicationType: "hip" | "fthb" | "tmr";
}

type TabType = "application" | "documents" | "attachments" | "certificates";

export default function PDFPreviewModal({
  isOpen,
  onClose,
  onDownload,
  pdfDocument,
  title,
  applicationId,
  applicationType,
}: PDFPreviewModalProps) {
  const [mounted, setMounted] = useState(false);
  const [activeTab, setActiveTab] = useState<TabType>("application");
  const [isDownloadingZip, setIsDownloadingZip] = useState(false);

  const { uploadedDocuments, attachments, certificates, loading, resetData } = usePDFDocuments({
    applicationId,
    applicationType,
    activeTab
  });
  const isTMR = applicationType === "tmr";

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (isOpen) {
      setActiveTab("application");
      resetData();
    }
  }, [isOpen]);

  const handleDownloadDocument = (fileName: string) => {
    const url = getDocumentUrl(fileName);
    window.open(url, '_blank');
  };

  const handleDownloadAgreement = (fileName: string) => {
    const url = getAgreementUrl(fileName);
    window.open(url, '_blank');
  };

  const handleDownloadSiteVisit = (fileName: string) => {
    const url = getSiteVisitUrl(fileName);
    window.open(url, '_blank');
  };

  const handleQutationsLink = (fileName: string) => {
    const url = getQuotationUrl(fileName);
    window.open(url, '_blank');
  };

  const handleDownloadPhoto = (fileUrl: string) => {
    const url = getMaintenancePhotoUrl(fileUrl);
    window.open(url, '_blank');
  };

  const handleDownloadAllAsZip = async () => {
    setIsDownloadingZip(true);

    try {
      const zip = new JSZip();


      const pdfBlob = await pdf(pdfDocument).toBlob();
      zip.file(`Application_${applicationId}.pdf`, pdfBlob);


      await loadMissingDocumentsIfNeeded();


      await addAllDocumentsToZip(zip);


      if (Object.keys(zip.files).length <= 1) {
        alert("No additional documents were found to include in the ZIP.");
        return;
      }


      const zipBlob = await zip.generateAsync({ type: "blob" });
      const url = URL.createObjectURL(zipBlob);

      const link = document.createElement("a");
      link.href = url;
      link.download = `Application_${applicationId}_AllDocuments.zip`;
      link.click();


      URL.revokeObjectURL(url);
    } catch (error) {
      console.error("ZIP generation failed:", error);
      alert("Failed to create ZIP file. Please check the console for details.");
    } finally {
      setIsDownloadingZip(false);
    }
  };

  async function loadMissingDocumentsIfNeeded() {
    const promises: Promise<any>[] = [];
    const loaders: Array<(res: any) => void> = [];
    if (
      certificates.quotations.length === 0 ||
      certificates.agreements.length === 0 ||
      certificates.siteVisits.length === 0
    ) {
      promises.push(
        Promise.all([
          documentService.getQuotations(applicationId),
          documentService.getAgreements(applicationId),
          documentService.getSiteVisits(applicationId),
        ]),
      );
      loaders.push((res: any[]) => {
        const [q, a, s] = res;
        certificates.quotations = Array.isArray(q.data.data) ? q.data.data : [];
        certificates.agreements =
          Array.isArray(a.data.data) ? a.data.data : a.data.data?.documents || [];
        certificates.siteVisits = Array.isArray(s.data.data) ? s.data.data : [];
      });
    }


    if (uploadedDocuments.length === 0 && applicationType !== "tmr") {
      promises.push(
        applicationType === "fthb"
          ? documentService.getFTHBDocuments(applicationId)
          : documentService.getHIPDocuments(applicationId),
      );
      loaders.push((res) => {
        if (res.data?.success) {
          const docs = res.data.data || [];
          uploadedDocuments.splice(0, uploadedDocuments.length, ...docs);
        }
      });
    }


    if (applicationType === "tmr" && attachments.length === 0) {
      promises.push(documentService.getTMRAttachments(applicationId));
      loaders.push((res) => {
        if (res.data?.success) {
          const atts = res.data.data || [];

          attachments.splice(0, attachments.length, ...atts);
        }
      });
    }

    if (promises.length === 0) return;

    const results = await Promise.all(promises);
    results.forEach((res, i) => loaders[i]?.(res));
  }

  async function addAllDocumentsToZip(zip: JSZip) {

    for (const q of certificates.quotations) {
      if (q.status !== "Approved") continue;
      const filename = getSafeFilename(q);
      const url = getQuotationUrl(q.file_name);
      await addFileToZip(zip, url, `Quotations/${filename}`, `Quotation ${filename}`);
    }


    for (const a of certificates.agreements) {
      const filename = getSafeFilename(a);
      const url = getAgreementUrl(a.file_name);
      await addFileToZip(zip, url, `Agreements/${filename}`, `Agreement ${filename}`);
    }


    for (const sv of certificates.siteVisits) {
      for (const photo of sv.photos || []) {
        const filename = photo.fileName;
        const url = getSiteVisitUrl(filename);
        const safeName = photo.originalName || filename;
        await addFileToZip(zip, url, `SiteVisits/${filename}`, `Site visit photo ${filename}`);
      }
    }


    for (const doc of uploadedDocuments) {
      console.log(doc)
      const filename = getSafeFilename(doc);

      const url = (doc as any).url || getDocumentUrl?.(filename);
      await addFileToZip(zip, url, `Documents/${doc.document_type}/${filename}`, `Uploaded doc ${filename}`);
    }


    for (const att of attachments) {

      const filename = getSafeFilename(att);
      const url = att.url || getMaintenancePhotoUrl?.(filename);

      if (url) {
        await addFileToZip(zip, url, `Attachments/${filename}`, `Attachment ${filename}`);
      } else {
        console.warn("Attachment URL is invalid for:", att);
      }
    }
  }

  if (!isOpen || !mounted) return null;

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
      <div className="bg-white rounded-lg shadow-xl w-[90vw] h-[90vh] flex flex-col">
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <h2 className="text-xl font-semibold text-gray-800">{title}</h2>
          <div className="flex gap-3">
            <Button
              onClick={handleDownloadAllAsZip}
              disabled={isDownloadingZip}
              variant="primary"
            >
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
              </svg>
              {isDownloadingZip ? "Preparing ZIP..." : "Download All as ZIP"}
            </Button>
            {activeTab === "application" && (
              <Button
                onClick={onDownload}
                variant="primary"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                </svg>
                Download PDF
              </Button>
            )}
            <button
              onClick={onClose}
              className="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition-colors"
            >
              Close
            </button>
          </div>
        </div>

        <div className="flex border-b">
          <TabButton active={activeTab === "application"} onClick={() => setActiveTab("application")}>
            Application
          </TabButton>
          {!isTMR && (
            <TabButton active={activeTab === "documents"} onClick={() => setActiveTab("documents")}>
              Uploaded Documents
            </TabButton>
          )}
          {isTMR && (
            <TabButton active={activeTab === "attachments"} onClick={() => setActiveTab("attachments")}>
              Attachments
            </TabButton>
          )}
          <TabButton active={activeTab === "certificates"} onClick={() => setActiveTab("certificates")}>
            Certificates
          </TabButton>
        </div>

        <div className="flex-1 overflow-hidden relative">
          <div className={activeTab === "application" ? "block h-full" : "hidden"}>
            {mounted && (
              <PDFViewer width="100%" height="100%" showToolbar={false}>
                {pdfDocument}
              </PDFViewer>
            )}
          </div>

          {!isTMR && (
            <div className={activeTab === "documents" ? "block h-full overflow-auto p-6" : "hidden"}>
              <UploadedDocumentsTab
                loading={loading}
                documents={uploadedDocuments}
                onDownload={handleDownloadDocument}
              />
            </div>
          )}

          {isTMR && (
            <div className={activeTab === "attachments" ? "block h-full overflow-auto p-6" : "hidden"}>
              <AttachmentsTab
                loading={loading}
                attachments={attachments}
                onDownload={handleDownloadPhoto}
              />
            </div>
          )}

          <div className={activeTab === "certificates" ? "block h-full overflow-auto p-6" : "hidden"}>
            <CertificatesTab
              isTMR={isTMR}
              loading={loading}
              quotations={certificates.quotations}
              agreements={certificates.agreements}
              siteVisits={certificates.siteVisits}
              onDownloadQuotation={handleQutationsLink}
              onDownloadAgreement={handleDownloadAgreement}
              onDownloadSiteVisit={handleDownloadSiteVisit}
            />
          </div>
        </div>
      </div>
    </div>
  );
}
