
import React, { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { FileDown, Loader2 } from 'lucide-react';
import { useToast } from '@/components/ui/use-toast';
import { generateViolationStatusPDF } from '@/lib/violationPdfGenerator';

export default function ViolationStatusExportDialog({ open, onOpenChange, violations = [], preselectedStatus = 'all' }) {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [includeTimeline, setIncludeTimeline] = useState(true);
  const [includeImages, setIncludeImages] = useState(true);
  const [statusFilter, setStatusFilter] = useState(preselectedStatus);

  const handleExport = async () => {
    setLoading(true);
    try {
      const doc = await generateViolationStatusPDF(violations, {
          pageSize: 'letter',
          clientName: violations[0]?.clients?.name || 'Association Status Report',
          includeTimeline,
          includeImages,
          statusFilter
      });
      
      doc.save(`Status_Report_${new Date().toISOString().split('T')[0]}.pdf`);
      toast({ title: "Export Successful", description: "Status report downloaded." });
      onOpenChange(false);
    } catch (error) {
      console.error("Export Error:", error);
      toast({ variant: "destructive", title: "Export Failed", description: "Could not generate report." });
    } finally {
      setLoading(false);
    }
  };

  const filteredCount = statusFilter === 'all' 
    ? violations.length 
    : statusFilter === 'open'
      ? violations.filter(v => ['open', 'escalated', 'recommended_for_fining'].includes((v.status || 'open').toLowerCase())).length
      : violations.filter(v => (v.status || 'open').toLowerCase() === statusFilter).length;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>Export by Status</DialogTitle>
          <DialogDescription>
            Generate a detailed PDF report organized by violation status.
          </DialogDescription>
        </DialogHeader>

        <div className="grid gap-6 py-4">
            <div className="space-y-2">
                <Label>Status to Export</Label>
                <Select value={statusFilter} onValueChange={setStatusFilter}>
                    <SelectTrigger>
                        <SelectValue placeholder="Select Status" />
                    </SelectTrigger>
                    <SelectContent>
                        <SelectItem value="all">All Statuses</SelectItem>
                        <SelectItem value="open">Open</SelectItem>
                        <SelectItem value="resolved">Resolved</SelectItem>
                    </SelectContent>
                </Select>
                <p className="text-xs text-slate-500">
                    Will export {filteredCount} violation{filteredCount !== 1 ? 's' : ''}.
                </p>
            </div>

            <div className="flex items-center space-x-2">
                <Checkbox id="timeline" checked={includeTimeline} onCheckedChange={setIncludeTimeline} />
                <Label htmlFor="timeline" className="cursor-pointer">Include Timeline & Activity History</Label>
            </div>

            <div className="flex items-center space-x-2">
                <Checkbox id="images" checked={includeImages} onCheckedChange={setIncludeImages} />
                <Label htmlFor="images" className="cursor-pointer">Include Evidence Photos</Label>
            </div>
        </div>

        <DialogFooter>
            <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
            <Button onClick={handleExport} disabled={loading || filteredCount === 0}>
                {loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <FileDown className="w-4 h-4 mr-2" />}
                Download Report
            </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
