import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { AlertTriangle, Loader2, RefreshCw, Eye } from "lucide-react";
import { format } from "date-fns";
import { parseLocalDate } from "@/lib/dateUtils";
import { Alert, AlertDescription } from "@/components/ui/alert";

export default function UnitViolationsTab({ unitId }: { unitId: string }) {
  const [violations, setViolations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedViolation, setSelectedViolation] = useState<any | null>(null);

  const fetchViolations = async () => {
    setLoading(true);
    setError(null);
    try {
      const { data, error: fetchError } = await supabase
        .from("violations")
        .select("*")
        .or(`unit_id.eq.${unitId},property_id.eq.${unitId}`)
        .order("created_at", { ascending: false });

      if (fetchError) throw fetchError;
      setViolations(data || []);
    } catch (err: any) {
      console.error("Error fetching violations:", err);
      setError(err.message || "Failed to fetch violations");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (unitId) fetchViolations();
  }, [unitId]);

  const getStatusColor = (status: string | null) => {
    switch ((status || "").toLowerCase()) {
      case "open": return "bg-warning/20 text-warning-foreground";
      case "closed": case "resolved": return "bg-success/20 text-success-foreground";
      default: return "bg-muted text-muted-foreground";
    }
  };

  if (loading) {
    return <div className="flex justify-center p-8"><Loader2 className="w-6 h-6 animate-spin text-muted-foreground" /></div>;
  }

  if (error) {
    return (
      <Alert variant="destructive">
        <AlertTriangle className="w-4 h-4" />
        <AlertDescription className="flex items-center justify-between">
          <span>{error}</span>
          <Button variant="outline" size="sm" onClick={fetchViolations}><RefreshCw className="w-4 h-4 mr-2" /> Retry</Button>
        </AlertDescription>
      </Alert>
    );
  }

  return (
    <div className="space-y-4">
      {violations.length === 0 ? (
        <div className="text-center p-8 bg-muted rounded-lg border">
          <AlertTriangle className="w-8 h-8 text-muted-foreground mx-auto mb-3" />
          <p className="font-medium">No violations found</p>
          <p className="text-sm text-muted-foreground mt-1">This unit currently has no reported violations.</p>
        </div>
      ) : (
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Date</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Due Date</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {violations.map((violation) => (
                <TableRow key={violation.id}>
                  <TableCell className="whitespace-nowrap">
                    {violation.violation_date ? format(new Date(violation.violation_date), "MMM d, yyyy") : format(new Date(violation.created_at), "MMM d, yyyy")}
                  </TableCell>
                  <TableCell className="font-medium">{violation.violation_type || violation.title || "General"}</TableCell>
                  <TableCell>
                    <Badge variant="secondary" className={getStatusColor(violation.status)}>
                      {violation.status || "Open"}
                    </Badge>
                  </TableCell>
                  <TableCell>{violation.due_date ? format(parseLocalDate(violation.due_date), "MMM d, yyyy") : "None"}</TableCell>
                  <TableCell className="text-right">
                    <Button variant="ghost" size="sm" onClick={() => setSelectedViolation(violation)}>
                      <Eye className="w-4 h-4 mr-2" /> View
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      <Dialog open={!!selectedViolation} onOpenChange={(open) => !open && setSelectedViolation(null)}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <AlertTriangle className="w-5 h-5 text-muted-foreground" /> Violation Details
            </DialogTitle>
          </DialogHeader>
          {selectedViolation && (
            <div className="space-y-4 mt-4">
              <div className="grid grid-cols-2 gap-4">
                <div><p className="text-sm text-muted-foreground">Type</p><p className="font-medium">{selectedViolation.violation_type || selectedViolation.title || "General"}</p></div>
                <div><p className="text-sm text-muted-foreground">Status</p><Badge variant="secondary" className={getStatusColor(selectedViolation.status)}>{selectedViolation.status || "Open"}</Badge></div>
                <div><p className="text-sm text-muted-foreground">Date Reported</p><p className="font-medium">{selectedViolation.violation_date ? format(parseLocalDate(selectedViolation.violation_date), "MMMM d, yyyy") : selectedViolation.created_at ? format(new Date(selectedViolation.created_at), "MMMM d, yyyy") : "N/A"}</p></div>
                <div><p className="text-sm text-muted-foreground">Due Date</p><p className="font-medium">{selectedViolation.due_date ? format(parseLocalDate(selectedViolation.due_date), "MMMM d, yyyy") : "None"}</p></div>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Description / Notes</p>
                <p className="bg-muted p-3 rounded-md mt-1 border">{selectedViolation.notes || selectedViolation.description || "No description provided."}</p>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
