import React, { useState } from 'react';
import { Button } from '@/components/ui/button';
import { FileDown, Loader2 } from 'lucide-react';
import jsPDF from 'jspdf';
import { format } from 'date-fns';
import { useToast } from '@/components/ui/use-toast';
import { prepareTimelineImages, calculateImageDimensions } from '@/lib/violationTimelineImageUtils';

export default function ViolationTimelineExportButton({ violation, entries = [] }) {
  const [loading, setLoading] = useState(false);
  const { toast } = useToast();

  const handleExport = async () => {
    if (!violation || entries.length === 0) {
      toast({ title: "No Data", description: "No timeline entries to export.", variant: "destructive" });
      return;
    }
    setLoading(true);
    try {
      const sortedEntries = [...entries].sort((a, b) => new Date(a.date || a.created_at) - new Date(b.date || b.created_at));
      const { enrichedEntries, successCount } = await prepareTimelineImages(sortedEntries, () => {});
      const doc = new jsPDF();
      const pageWidth = doc.internal.pageSize.getWidth();
      const pageHeight = doc.internal.pageSize.getHeight();
      const margin = 20;
      let y = margin;

      doc.setFontSize(18); doc.setFont('helvetica', 'bold'); doc.text("Violation Activity Timeline", margin, y); y += 8;
      doc.setFontSize(10); doc.setFont('helvetica', 'normal');
      doc.text(`Property: ${violation.address || "Unknown"}`, margin, y); y += 5;
      doc.text(`Generated: ${format(new Date(), 'MMM d, yyyy')}`, margin, y); y += 10;
      doc.line(margin, y, pageWidth - margin, y); y += 10;

      for (const entry of enrichedEntries) {
        const dateStr = format(new Date(entry.date || entry.created_at), 'MMM d, yyyy');
        const desc = entry.description || 'No description';
        const descLines = doc.splitTextToSize(desc, pageWidth - margin * 2 - 10);
        const blockHeight = 20 + descLines.length * 5 + (entry.imageData ? 100 : 0);
        if (y + blockHeight > pageHeight - margin) { doc.addPage(); y = margin; }
        doc.setFontSize(9); doc.setFont('helvetica', 'bold'); doc.text(dateStr, margin, y); y += 6;
        doc.setFont('helvetica', 'normal'); doc.text(descLines, margin + 5, y); y += descLines.length * 5 + 5;
        if (entry.imageData) {
          try {
            const dims = calculateImageDimensions(entry.imageData.width, entry.imageData.height, 150, 100);
            doc.addImage(entry.imageData.data, entry.imageData.format, margin + 5, y, dims.width, dims.height);
            y += dims.height + 5;
          } catch (e) { /* skip */ }
        }
        doc.line(margin, y, pageWidth - margin, y); y += 10;
      }

      const filename = `Timeline_${(violation.address || 'export').replace(/[^a-z0-9]/gi, '_')}_${format(new Date(), 'yyyy-MM-dd')}.pdf`;
      doc.save(filename);
      toast({ title: "Export Complete", description: `Downloaded with ${successCount} images.` });
    } catch (error) {
      toast({ title: "Export Failed", variant: "destructive" });
    } finally { setLoading(false); }
  };

  return (
    <Button size="sm" variant="outline" onClick={handleExport} disabled={loading || entries.length === 0} className="flex items-center gap-2">
      {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <FileDown className="w-4 h-4" />}
      <span className="hidden sm:inline">Export PDF</span>
    </Button>
  );
}
