
import React, { useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Switch } from '@/components/ui/switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Progress } from '@/components/ui/progress';
import { FileDown, Loader2, Eye, LayoutGrid, List, History, XCircle } from 'lucide-react';
import { generateViolationsPDF, generateViolationTimelinePDF } from '@/lib/violationPdfGenerator';
import { useToast } from '@/components/ui/use-toast';
import { useViolationReportOptimization } from '@/hooks/useViolationReportOptimization';

export default function ViolationExportDialog({ open, onOpenChange, violations = [] }) {
  const { toast } = useToast();
  const { isGenerating, progress, startGeneration, cancelGeneration } = useViolationReportOptimization();
  
  const [settings, setSettings] = useState({
    layout: 'grid', 
    pageSize: 'letter',
    includeImages: true,
    includeTimeline: true,
    colorScheme: 'default'
  });

  const handleExport = async (action = 'download') => {
    if (isGenerating) return;
    
    if (!violations || violations.length === 0) {
      toast({ variant: "destructive", title: "Nothing to export", description: "No violations selected or available." });
      return;
    }

    try {
      const clientName = (violations[0]?.clients?.name) || 'Association Report';
      
      const generatorFn = settings.layout === 'timeline' ? generateViolationTimelinePDF : generateViolationsPDF;
      
      const doc = await startGeneration(violations, {
          ...settings,
          clientName: clientName
      }, generatorFn);
      
      if (!doc) return;

      const dateStr = new Date().toISOString().split('T')[0];

      if (action === 'preview') {
        window.open(URL.createObjectURL(doc.output('blob')), '_blank');
      } else {
        const prefix = settings.layout === 'timeline' ? 'Timeline_Report' : 'Violations_Report';
        doc.save(`${prefix}_${dateStr}.pdf`);
        toast({ title: "Export Successful", description: "Your PDF report has been downloaded." });
        onOpenChange(false);
      }
    } catch (error) {
       console.error("Export dialog error:", error);
       if (error?.message !== 'Report generation cancelled') {
           toast({ 
             variant: "destructive", 
             title: "Export Failed", 
             description: error?.message || "An unexpected error occurred during PDF generation." 
           });
       }
    }
  };

  return (
    <Dialog open={open} onOpenChange={(val) => { if(!isGenerating) onOpenChange(val); }}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>Export Violations PDF</DialogTitle>
          <DialogDescription>
            {isGenerating 
              ? `Generating report for ${violations?.length || 0} records...` 
              : `Configure options for the violation report. Exporting ${violations?.length || 0} record(s).`
            }
          </DialogDescription>
        </DialogHeader>

        {isGenerating ? (
            <div className="py-8 space-y-4">
                <Progress value={progress} className="h-3" />
                <p className="text-center text-sm text-muted-foreground">{progress}% Complete</p>
                <div className="flex justify-center">
                    <Button variant="outline" size="sm" onClick={cancelGeneration} className="text-red-500 hover:text-red-600 hover:bg-red-50">
                        <XCircle className="w-4 h-4 mr-2" /> Cancel Operation
                    </Button>
                </div>
            </div>
        ) : (
            <div className="grid gap-6 py-4">
              <div className="space-y-3">
                <Label>Report Type</Label>
                <RadioGroup 
                   value={settings.layout} 
                   onValueChange={(val) => setSettings(s => ({ ...s, layout: val }))}
                   className="grid grid-cols-3 gap-4"
                >
                  <div>
                    <RadioGroupItem value="grid" id="layout-grid" className="peer sr-only" />
                    <Label htmlFor="layout-grid" className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary cursor-pointer h-full">
                      <LayoutGrid className="mb-2 h-6 w-6" /> <span className="text-xs text-center">Grid</span>
                    </Label>
                  </div>
                  <div>
                    <RadioGroupItem value="list" id="layout-list" className="peer sr-only" />
                    <Label htmlFor="layout-list" className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary cursor-pointer h-full">
                      <List className="mb-2 h-6 w-6" /> <span className="text-xs text-center">List</span>
                    </Label>
                  </div>
                  <div>
                    <RadioGroupItem value="timeline" id="layout-timeline" className="peer sr-only" />
                    <Label htmlFor="layout-timeline" className="flex flex-col items-center justify-between rounded-md border-2 border-muted bg-popover p-4 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary cursor-pointer h-full">
                      <History className="mb-2 h-6 w-6" /> <span className="text-xs text-center">Timeline</span>
                    </Label>
                  </div>
                </RadioGroup>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Page Size</Label>
                  <Select value={settings.pageSize} onValueChange={(val) => setSettings(s => ({ ...s, pageSize: val }))}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="letter">Letter (8.5 x 11)</SelectItem>
                      <SelectItem value="a4">A4</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              {settings.layout !== 'timeline' && (
                <div className="space-y-4">
                    <div className="flex items-center justify-between space-x-2 border p-3 rounded-md bg-slate-50">
                        <div className="space-y-0.5"><Label>Include Evidence Images</Label></div>
                        <Switch checked={settings.includeImages} onCheckedChange={(val) => setSettings(s => ({ ...s, includeImages: val }))} />
                    </div>
                    <div className="flex items-center justify-between space-x-2 border p-3 rounded-md bg-slate-50">
                        <div className="space-y-0.5"><Label>Include Timeline History</Label></div>
                        <Switch checked={settings.includeTimeline} onCheckedChange={(val) => setSettings(s => ({ ...s, includeTimeline: val }))} />
                    </div>
                </div>
              )}
            </div>
        )}

        {!isGenerating && (
            <DialogFooter className="gap-2 sm:gap-0">
              <Button variant="outline" onClick={() => handleExport('preview')} disabled={isGenerating}>
                 <Eye className="w-4 h-4 mr-2" /> Preview
              </Button>
              <Button onClick={() => handleExport('download')} disabled={isGenerating}>
                 <FileDown className="w-4 h-4 mr-2" /> Download
              </Button>
            </DialogFooter>
        )}
      </DialogContent>
    </Dialog>
  );
}
