import React, { useState, useMemo } from 'react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { format } from 'date-fns';
import { MoreHorizontal, Trash2, ArrowUpDown } from 'lucide-react';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenuSeparator } from '@/components/ui/dropdown-menu';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/components/ui/use-toast';

export function ViolationTableView({ violations, selectedIds, onToggleSelect, onToggleSelectAll, onViewDetails, onRefresh }) {
  const { toast } = useToast();
  const [violationToDelete, setViolationToDelete] = useState(null);
  const [sortConfig, setSortConfig] = useState({ key: 'created_at', direction: 'desc' });
  const isAllSelected = violations.length > 0 && selectedIds.length === violations.length;

  const handleSort = (key) => {
    setSortConfig((prev) => ({
      key,
      direction: prev.key === key && prev.direction === 'asc' ? 'desc' : 'asc',
    }));
  };

  const getSortValue = (v, key) => {
    switch (key) {
      case 'type': return (v.violation_type || v.title || '').toLowerCase();
      case 'address': return (v.owners?.property_address || v.address || '').toLowerCase();
      case 'status': return (v.status || '').toLowerCase();
      case 'stage': return (v.stage || '').toLowerCase();
      case 'association': return (v.associations?.name || '').toLowerCase();
      case 'violation_date': return new Date(v.violation_date || v.created_at).getTime();
      case 'created_at': return new Date(v.created_at).getTime();
      case 'due_date': return v.due_date ? new Date(v.due_date).getTime() : 0;
      default: return '';
    }
  };

  const sortedViolations = useMemo(() => {
    const items = [...violations];
    if (!sortConfig.key) return items;
    items.sort((a, b) => {
      const av = getSortValue(a, sortConfig.key);
      const bv = getSortValue(b, sortConfig.key);
      if (av < bv) return sortConfig.direction === 'asc' ? -1 : 1;
      if (av > bv) return sortConfig.direction === 'asc' ? 1 : -1;
      return 0;
    });
    return items;
  }, [violations, sortConfig]);

  const SortBtn = ({ k, label }) => (
    <Button variant="ghost" onClick={() => handleSort(k)} className="h-7 px-1 -ml-1 font-medium text-xs">
      {label} <ArrowUpDown className="ml-1 h-3 w-3" />
    </Button>
  );

  const getStageLabel = (stage) => {
     switch(stage) {
        case 'first_notice': return '1st Notice';
        case 'second_notice': return '2nd Notice';
        case 'third_final': return 'Final';
        default: return stage || 'N/A';
     }
  };

  const handleDelete = async () => {
     if (!violationToDelete) return;
     try {
       const { error } = await supabase.from('violations').delete().eq('id', violationToDelete.id);
       if (error) throw error;
       toast({ title: "Violation Deleted" });
       if (onRefresh) onRefresh();
     } catch (error) {
       toast({ variant: "destructive", title: "Error", description: "Failed to delete violation." });
     } finally {
       setViolationToDelete(null);
     }
  };

  return (
    <>
      <div className="rounded-md border bg-card w-full overflow-hidden">
        <div className="w-full overflow-x-auto">
          <Table className="w-full text-sm">
            <TableHeader>
              <TableRow className="bg-muted/50">
                <TableHead className="w-[40px] text-center p-2">
                  <Checkbox checked={isAllSelected} onCheckedChange={onToggleSelectAll} disabled={violations.length === 0} className="w-4 h-4" />
                </TableHead>
                <TableHead className="p-2 whitespace-nowrap"><SortBtn k="type" label="Type" /></TableHead>
                <TableHead className="p-2 min-w-[120px]"><SortBtn k="address" label="Address" /></TableHead>
                <TableHead className="p-2"><SortBtn k="status" label="Status" /></TableHead>
                <TableHead className="p-2 hidden xl:table-cell">Tags</TableHead>
                <TableHead className="p-2"><SortBtn k="stage" label="Stage" /></TableHead>
                <TableHead className="p-2 whitespace-nowrap"><SortBtn k="created_at" label="Original" /></TableHead>
                <TableHead className="p-2 whitespace-nowrap"><SortBtn k="violation_date" label="Violation" /></TableHead>
                <TableHead className="p-2 whitespace-nowrap"><SortBtn k="due_date" label="Due" /></TableHead>
                <TableHead className="p-2 hidden xl:table-cell"><SortBtn k="association" label="Association" /></TableHead>
                <TableHead className="p-2 text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {sortedViolations.length === 0 ? (
                <TableRow><TableCell colSpan={11} className="h-24 text-center text-muted-foreground">No violations found.</TableCell></TableRow>
              ) : (
                sortedViolations.map((v) => {
                  const isSelected = selectedIds.includes(v.id);
                  return (
                    <TableRow key={v.id} className={`transition-colors ${isSelected ? "bg-primary/5 hover:bg-primary/10" : "hover:bg-muted/50"}`}>
                      <TableCell className="text-center p-2"><Checkbox checked={isSelected} onCheckedChange={() => onToggleSelect(v.id)} className="w-4 h-4" /></TableCell>
                      <TableCell className="font-medium p-2 max-w-[120px] truncate">{v.violation_type || v.title}</TableCell>
                      <TableCell className="p-2 max-w-[200px] truncate text-muted-foreground">{v.owners?.property_address || v.address || '-'}</TableCell>
                      <TableCell className="p-2">
                        <Badge variant={v.status === 'open' || v.status === 'recommended_for_fining' ? 'destructive' : v.status === 'resolved' ? 'default' : 'secondary'} className="capitalize text-xs">{v.status}</Badge>
                      </TableCell>
                      <TableCell className="p-2 hidden xl:table-cell">
                        <div className="flex flex-wrap gap-1 max-w-[180px]">
                          {(v.tags || []).slice(0, 3).map((tag, idx) => (
                            <Badge key={idx} variant="outline" className="text-[10px] font-normal">{tag}</Badge>
                          ))}
                          {(v.tags || []).length > 3 && <span className="text-[10px] text-muted-foreground">+{v.tags.length - 3}</span>}
                        </div>
                      </TableCell>
                      <TableCell className="p-2"><Badge variant="outline" className="font-normal text-xs">{getStageLabel(v.stage)}</Badge></TableCell>
                      <TableCell className="text-muted-foreground p-2 whitespace-nowrap">{format(new Date(v.created_at), 'MMM d, yy')}</TableCell>
                      <TableCell className="text-muted-foreground p-2 whitespace-nowrap">{format(new Date(v.violation_date || v.created_at), 'MMM d, yy')}</TableCell>
                      <TableCell className="text-muted-foreground p-2 whitespace-nowrap">{v.due_date ? format(new Date(v.due_date), 'MMM d, yy') : '-'}</TableCell>
                      <TableCell className="text-muted-foreground p-2 hidden xl:table-cell max-w-[120px] truncate">{v.associations?.name || '-'}</TableCell>
                      <TableCell className="text-right p-2">
                         <DropdownMenu>
                            <DropdownMenuTrigger asChild><Button variant="ghost" className="h-8 w-8 p-0"><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                               <DropdownMenuItem onClick={() => onViewDetails(v)}>View Details</DropdownMenuItem>
                               <DropdownMenuSeparator />
                               <DropdownMenuItem className="text-destructive" onClick={(e) => { e.stopPropagation(); setViolationToDelete(v); }}><Trash2 className="w-4 h-4 mr-2" /> Delete</DropdownMenuItem>
                            </DropdownMenuContent>
                         </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  );
                })
              )}
            </TableBody>
          </Table>
        </div>
      </div>

      <AlertDialog open={!!violationToDelete} onOpenChange={(open) => !open && setViolationToDelete(null)}>
        <AlertDialogContent>
          <AlertDialogHeader><AlertDialogTitle>Delete Violation</AlertDialogTitle><AlertDialogDescription>Are you sure? This action cannot be undone.</AlertDialogDescription></AlertDialogHeader>
          <AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={handleDelete} className="bg-destructive">Delete</AlertDialogAction></AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}

export default ViolationTableView;
