import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Download, Loader2 } from 'lucide-react';
import { jsPDF } from 'jspdf';
import { format } from 'date-fns';

export function PublicFormReportPdfExport({ reportData, templateData, fileName = 'Submission_Report' }) {
  const [generating, setGenerating] = useState(false);

  const generatePDF = () => {
    setGenerating(true);
    try {
      const doc = new jsPDF();
      const pageWidth = doc.internal.pageSize.getWidth();
      const margin = 20;
      let yPos = 20;

      // Header
      doc.setFontSize(18);
      doc.setFont('helvetica', 'bold');
      doc.text(templateData?.title || 'Form Submission Report', margin, yPos);
      yPos += 10;

      doc.setFontSize(10);
      doc.setFont('helvetica', 'normal');
      doc.setTextColor(100);
      const subDate = reportData?.metadata?.submitted_at
        ? format(new Date(reportData.metadata.submitted_at), 'PPP pp')
        : 'N/A';

      doc.text(`Submitted: ${subDate}`, margin, yPos);
      doc.text(`ID: ${reportData?.metadata?.submission_id || 'N/A'}`, pageWidth - margin, yPos, { align: 'right' });
      yPos += 20;

      doc.setDrawColor(200);
      doc.line(margin, yPos - 10, pageWidth - margin, yPos - 10);

      // Content
      doc.setTextColor(0);

      const fields = reportData?.fields_snapshot || [];
      const values = reportData?.submission_values || {};

      fields.forEach((field) => {
        if (yPos > 270) {
          doc.addPage();
          yPos = 20;
        }

        if (field.type === 'spacer' || field.type === 'horizontal_line') return;

        if (field.type === 'header') {
          yPos += 5;
          doc.setFontSize(14);
          doc.setFont('helvetica', 'bold');
          doc.setFillColor(245, 247, 250);
          doc.rect(margin, yPos - 12, pageWidth - (margin * 2), 16, 'F');
          doc.text(field.label || field.content || '', margin + 5, yPos);
          yPos += 15;
          return;
        }

        if (field.type === 'paragraph') {
          doc.setFontSize(10);
          doc.setFont('helvetica', 'italic');
          doc.setTextColor(80);
          const text = doc.splitTextToSize(field.label || field.content || '', pageWidth - (margin * 2));
          doc.text(text, margin, yPos);
          yPos += (text.length * 5) + 10;
          doc.setTextColor(0);
          return;
        }

        // Standard Fields
        doc.setFontSize(9);
        doc.setFont('helvetica', 'bold');
        doc.setTextColor(100);
        doc.text((field.label || 'Field').toUpperCase(), margin, yPos);
        yPos += 5;

        doc.setFontSize(11);
        doc.setFont('helvetica', 'normal');
        doc.setTextColor(0);

        let value = values[field.id];

        if (field.type === 'signature' && value) {
          try {
            doc.addImage(value, 'PNG', margin, yPos, 100, 40);
            yPos += 45;
          } catch (e) {
            doc.text("[Signature Image]", margin, yPos);
            yPos += 10;
          }
        } else if (field.type === 'checkbox') {
          doc.text(value ? 'Yes' : 'No', margin, yPos);
          yPos += 10;
        } else if (field.type === 'time' && typeof value === 'object') {
          doc.text(value.time || '', margin, yPos);
          yPos += 10;
        } else {
          const strValue = value !== undefined && value !== null ? String(value) : '';
          const text = doc.splitTextToSize(strValue, pageWidth - (margin * 2));
          doc.text(text, margin, yPos);
          yPos += (text.length * 6) + 10;
        }

        yPos += 5;
      });

      // Footer
      const pageCount = doc.internal.getNumberOfPages();
      for (let i = 1; i <= pageCount; i++) {
        doc.setPage(i);
        doc.setFontSize(8);
        doc.setTextColor(150);
        doc.text(`Page ${i} of ${pageCount}`, pageWidth / 2, 290, { align: 'center' });
      }

      doc.save(`${fileName}_${format(new Date(), 'yyyyMMdd')}.pdf`);
    } catch (err) {
      console.error("PDF Generation failed:", err);
    } finally {
      setGenerating(false);
    }
  };

  return (
    <Button variant="outline" size="sm" onClick={generatePDF} disabled={generating}>
      {generating ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Download className="w-4 h-4 mr-2" />}
      Download PDF
    </Button>
  );
}

export default PublicFormReportPdfExport;
