import React from 'react';
import { Button } from '@/components/ui/button';
import { FileDown, Loader2, XCircle } from 'lucide-react';
import { generateViolationsPDF } from '@/lib/violationPdfGenerator';
import { cn } from '@/lib/utils';
import { useToast } from '@/components/ui/use-toast';
import { useViolationReportOptimization } from '@/hooks/useViolationReportOptimization';

export function ViolationReportPdfExport({ 
  violations = [], 
  clientName, 
  dateRange, 
  buttonVariant = "outline", 
  buttonClassName 
}) {
  const { toast } = useToast();
  const { isGenerating, progress, startGeneration, cancelGeneration } = useViolationReportOptimization();

  const handleExport = async () => {
    if (isGenerating) return;
    
    if (!violations || violations.length === 0) {
      toast({ variant: "destructive", title: "No Data", description: "No violations to export." });
      return;
    }

    try {
      // Safe fallback for clientName if missing
      const effectiveClientName = clientName || (violations[0]?.clients?.name) || 'Association Report';

      const settings = {
        layout: 'grid',
        pageSize: 'letter',
        includeImages: true,
        includeTimeline: true,
        clientName: effectiveClientName,
        dateRange
      };
      
      const doc = await startGeneration(violations, settings, generateViolationsPDF);
      if (doc) {
          const dateStr = new Date().toISOString().split('T')[0];
          doc.save(`Violation_Report_${dateStr}.pdf`);
          toast({ title: "Success", description: "Report generated successfully." });
      }
    } catch (error) {
      console.error("Quick export error:", error);
      if (error?.message !== 'Report generation cancelled') {
        toast({ 
          variant: "destructive", 
          title: "Export Error", 
          description: error?.message || "Failed to generate PDF report. Please try again." 
        });
      }
    }
  };

  if (isGenerating) {
      return (
        <Button variant="destructive" size="sm" onClick={cancelGeneration} className={cn("gap-2 min-w-[140px]", buttonClassName)}>
           <XCircle className="w-4 h-4" /> Cancel ({progress}%)
        </Button>
      );
  }

  return (
    <Button 
      variant={buttonVariant} 
      className={cn("gap-2", buttonClassName)}
      onClick={handleExport}
      disabled={!violations || violations.length === 0 || isGenerating}
    >
      <FileDown className="w-4 h-4" />
      Export PDF
    </Button>
  );
}