import React, { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/components/ui/use-toast';
import { Button } from '@/components/ui/button';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { AlertCircle, Plus, Pencil, Trash2, Loader2, FileText } from 'lucide-react';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import ViolationTypeDialog from './ViolationTypeDialog';

export default function ViolationTypeManager({ associationId }) {
  const { toast } = useToast();
  const [types, setTypes] = useState([]);
  const [loading, setLoading] = useState(false);
  const [editingType, setEditingType] = useState(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [deleteId, setDeleteId] = useState(null);

  const fetchTypes = async () => {
    if (!associationId) return;
    setLoading(true);
    try {
      const { data, error } = await supabase.from('violation_types').select('*').eq('association_id', associationId).order('category');
      if (error) throw error;
      setTypes(data || []);
    } catch (err) {
      toast({ variant: 'destructive', title: 'Error', description: 'Could not load violation types.' });
    } finally { setLoading(false); }
  };

  useEffect(() => { fetchTypes(); }, [associationId]);

  const handleDelete = async () => {
    if (!deleteId) return;
    try {
      const { error } = await supabase.from('violation_types').delete().eq('id', deleteId);
      if (error) throw error;
      toast({ title: 'Deleted' });
      fetchTypes();
    } catch (err) {
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to delete.' });
    } finally { setDeleteId(null); }
  };

  if (!associationId) {
    return (<div className="flex flex-col items-center justify-center p-8 text-center bg-muted/50 rounded-lg border border-dashed"><AlertCircle className="w-8 h-8 text-muted-foreground mb-2" /><p className="text-muted-foreground">Please select an association to manage violation types.</p></div>);
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <div><h3 className="text-lg font-medium">Defined Violation Types</h3><p className="text-sm text-muted-foreground">Standard violations for quick selection when logging new violations.</p></div>
        <Button onClick={() => { setEditingType(null); setIsDialogOpen(true); }}><Plus className="w-4 h-4 mr-2" /> Add Type</Button>
      </div>

      {loading ? (
        <div className="flex justify-center py-8"><Loader2 className="w-6 h-6 animate-spin text-muted-foreground" /></div>
      ) : types.length === 0 ? (
        <div className="flex flex-col items-center justify-center p-8 bg-muted/30 rounded-lg border border-dashed">
          <FileText className="w-8 h-8 text-muted-foreground mb-2" /><p className="text-muted-foreground">No violation types defined yet.</p>
        </div>
      ) : (
        <div className="rounded-md border">
          <Table>
             <TableHeader><TableRow><TableHead>Category</TableHead><TableHead>Article/Section</TableHead><TableHead className="text-center">Cure Days</TableHead><TableHead className="text-center">Stages</TableHead><TableHead>Requested Action</TableHead><TableHead className="text-right">Actions</TableHead></TableRow></TableHeader>
            <TableBody>
              {types.map(t => (
                <TableRow key={t.id}>
                  <TableCell className="font-medium">{t.category}</TableCell>
                  <TableCell className="text-muted-foreground">{t.article_section || '-'}</TableCell>
                  <TableCell className="text-center text-muted-foreground">{t.cure_days ?? 14}</TableCell>
                  <TableCell className="text-center text-muted-foreground">{t.stage_count ?? 3}</TableCell>
                  <TableCell className="text-muted-foreground max-w-[200px] truncate">{t.requested_action || '-'}</TableCell>
                  <TableCell className="text-right">
                    <Button variant="ghost" size="icon" onClick={() => { setEditingType(t); setIsDialogOpen(true); }}><Pencil className="w-4 h-4" /></Button>
                    <Button variant="ghost" size="icon" className="text-destructive" onClick={() => setDeleteId(t.id)}><Trash2 className="w-4 h-4" /></Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      <ViolationTypeDialog open={isDialogOpen} onOpenChange={setIsDialogOpen} violationType={editingType} associationId={associationId} onSuccess={fetchTypes} />
      <AlertDialog open={!!deleteId} onOpenChange={(open) => !open && setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader><AlertDialogTitle>Delete Violation Type</AlertDialogTitle><AlertDialogDescription>This will remove this type. Existing violations won't be affected.</AlertDialogDescription></AlertDialogHeader>
          <AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={handleDelete} className="bg-destructive">Delete</AlertDialogAction></AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
