"use client";

import { useState } from "react";
import { FiDownload, FiEye } from "react-icons/fi";
import { downloadApplicationPDF, fetchApplicationData, generatePDFDocument, getFormTitle } from "@/src/utils/pdfGenerator";
import Button from "../admin/ui/button/Button";
import PDFPreviewModal from "./PDFPreviewModal";
import type { ReactElement } from "react";
import type { DocumentProps } from "@react-pdf/renderer";

interface PDFDownloadButtonProps {
  applicationId: number;
  applicationType: "hip" | "fthb" | "tmr";
}

export default function PDFDownloadButton({
  applicationId,
  applicationType,
}: PDFDownloadButtonProps) {
  const [isLoading, setIsLoading] = useState(false);
  const [showPreview, setShowPreview] = useState(false);
  const [pdfDocument, setPdfDocument] = useState<ReactElement<DocumentProps> | null>(null);
  const [formData, setFormData] = useState<any>(null);

  const handlePreview = async () => {
    setIsLoading(true);
    const result = await fetchApplicationData(applicationId, applicationType);
    
    if (!result.success || !result.data) {
      alert(result.error);
      setIsLoading(false);
      return;
    }

    setFormData(result.data);
    setPdfDocument(generatePDFDocument(result.data, applicationType));
    setShowPreview(true);
    setIsLoading(false);
  };

  const handleDownload = async () => {
    setIsLoading(true);
    const result = await downloadApplicationPDF(applicationId, applicationType);
    
    if (!result.success) {
      alert(result.error);
    }
    
    setIsLoading(false);
    setShowPreview(false);
  };

  return (
    <>
      <div className="flex gap-2">
        <Button
        variant="primaryOutline"
        className="text-nowrap" onClick={handlePreview} disabled={isLoading}>
          {isLoading ? (
            <>
              <svg className="animate-spin h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              <span>Loading...</span>
            </>
          ) : (
            <>
              <FiEye size={14} />
              <span>View Attachements </span>
            </>
          )}
        </Button>
      </div>

      {pdfDocument && (
        <PDFPreviewModal
          isOpen={showPreview}
          onClose={() => setShowPreview(false)}
          onDownload={handleDownload}
          pdfDocument={pdfDocument}
          title={getFormTitle(applicationType)}
          applicationId={applicationId}
          applicationType={applicationType}
        />
      )}
    </>
  );
}
