import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Upload, FileUp, ListPlus, Trash2, Loader2, AlertCircle, CheckCircle } from 'lucide-react';
import ViolationTimelineImportForm from './ViolationTimelineImportForm';
import { useViolationTimelineImport } from '@/hooks/useViolationTimelineImport';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/components/ui/use-toast';
import { cn } from '@/lib/utils';
import { validateTimelineEntry } from '@/lib/violationUtils';

export default function ViolationTimelineImportDialog({ open, onOpenChange, preSelectedViolationId, onSuccess }) {
  const { toast } = useToast();
  const [activeTab, setActiveTab] = useState('manual');
  const [selectedViolationId, setSelectedViolationId] = useState(preSelectedViolationId || '');
  const [violations, setViolations] = useState([]);
  const [pendingEntries, setPendingEntries] = useState([]);
  const { saveEntries, loading, importErrors } = useViolationTimelineImport(() => { onOpenChange(false); setPendingEntries([]); if (onSuccess) onSuccess(); });

  useEffect(() => {
    if (open && !preSelectedViolationId) {
      supabase.from('violations').select('id, address, violation_type, created_at').order('created_at', { ascending: false }).limit(50)
        .then(({ data }) => { if (data) setViolations(data); });
    } else if (preSelectedViolationId) { setSelectedViolationId(preSelectedViolationId); }
  }, [open, preSelectedViolationId]);

  const handleManualAdd = (entry) => setPendingEntries(prev => [...prev, entry]);
  const handleRemoveEntry = (index) => setPendingEntries(prev => prev.filter((_, i) => i !== index));

  const handleImport = () => {
    if (!selectedViolationId) { toast({ variant: "destructive", title: "Selection Required" }); return; }
    saveEntries(selectedViolationId, pendingEntries);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[700px] max-h-[85vh] flex flex-col">
        <DialogHeader><DialogTitle>Import Timeline Entries</DialogTitle><DialogDescription>Add historical entries to the violation timeline.</DialogDescription></DialogHeader>
        <div className="space-y-4 flex-1 overflow-y-auto pr-2">
            {!preSelectedViolationId && (
                <div className="space-y-2"><Label>Select Violation Target</Label>
                  <Select value={selectedViolationId} onValueChange={setSelectedViolationId}><SelectTrigger><SelectValue placeholder="Select a violation..." /></SelectTrigger>
                    <SelectContent>{violations.map(v => (<SelectItem key={v.id} value={v.id}>{v.address} - {v.violation_type}</SelectItem>))}</SelectContent>
                  </Select>
                </div>
            )}
            <ViolationTimelineImportForm onAddEntry={handleManualAdd} />
            {pendingEntries.length > 0 && (
                <div className="space-y-2">
                    <div className="flex justify-between items-center"><Label>Pending ({pendingEntries.length})</Label><Button variant="ghost" size="sm" onClick={() => setPendingEntries([])} className="text-xs text-destructive">Clear All</Button></div>
                    <div className="border rounded-md max-h-[200px] overflow-y-auto">
                        <Table><TableHeader><TableRow><TableHead>Date</TableHead><TableHead>Status</TableHead><TableHead>Description</TableHead><TableHead className="w-[50px]"></TableHead></TableRow></TableHeader>
                        <TableBody>{pendingEntries.map((entry, idx) => {
                            const issues = validateTimelineEntry(entry);
                            return (<TableRow key={idx} className={cn(issues.length > 0 && "bg-destructive/5")}>
                                <TableCell className="text-xs">{entry.entry_date}</TableCell><TableCell className="text-xs capitalize">{entry.status}</TableCell>
                                <TableCell className="text-xs max-w-[200px] truncate">{entry.description}{issues.length > 0 && <div className="text-[10px] text-destructive flex items-center mt-1"><AlertCircle className="w-3 h-3 mr-1" />{issues[0]}</div>}</TableCell>
                                <TableCell><Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => handleRemoveEntry(idx)}><Trash2 className="w-3 h-3" /></Button></TableCell>
                            </TableRow>);
                        })}</TableBody></Table>
                    </div>
                </div>
            )}
        </div>
        <DialogFooter className="mt-4 pt-4 border-t">
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={handleImport} disabled={pendingEntries.length === 0 || loading}>{loading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <CheckCircle className="w-4 h-4 mr-2" />}Import {pendingEntries.length} Entries</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
