import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Search, AlertTriangle, Loader2, Eye, Filter } from "lucide-react";
import { format } from "date-fns";
import type { Tables } from "@/integrations/supabase/types";
import ClientViolationDetailDialog from "@/components/violations/ClientViolationDetailDialog";

type Violation = Tables<"violations"> & {
  units?: { unit_number: string } | null;
  associations?: { name: string } | null;
};

export default function ClientViolationsPage() {
  const [violations, setViolations] = useState<Violation[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  const [selectedViolation, setSelectedViolation] = useState<Violation | null>(null);

  const fetchViolations = async () => {
    setLoading(true);
    const { data } = await supabase
      .from("violations")
      .select("*, units(unit_number), associations(name)")
      .order("created_at", { ascending: false });
    setViolations(data || []);
    setLoading(false);
  };

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

  const statusColor = (s: string | null) => {
    switch (s) {
      case "open": return "destructive" as const;
      case "escalated": return "destructive" as const;
      case "pending": return "secondary" as const;
      case "resolved": case "closed": return "default" as const;
      default: return "secondary" as const;
    }
  };

  const priorityLabel = (p: string | null) => {
    switch (p) {
      case "critical": return <span className="text-destructive font-bold">Critical</span>;
      case "high": return <span className="text-destructive">High</span>;
      case "medium": return <span className="text-foreground">Medium</span>;
      case "low": return <span className="text-muted-foreground">Low</span>;
      default: return <span className="text-muted-foreground">—</span>;
    }
  };

  const filtered = violations.filter((v) => {
    const matchesSearch =
      v.title.toLowerCase().includes(search.toLowerCase()) ||
      (v.violation_type || "").toLowerCase().includes(search.toLowerCase()) ||
      (v.address || "").toLowerCase().includes(search.toLowerCase());
    const matchesStatus = statusFilter === "all" || v.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const openCount = violations.filter(v => v.status === "open" || v.status === "escalated" || v.status === "recommended_for_fining").length;
  const escalatedCount = violations.filter(v => v.status === "escalated").length;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-foreground flex items-center gap-2">
          <AlertTriangle className="w-7 h-7 text-destructive" /> Violations
        </h1>
        <p className="text-muted-foreground mt-1">
          View and track violation records for your associations.
          {openCount > 0 && <span className="ml-2 text-destructive font-medium">{openCount} open</span>}
          {escalatedCount > 0 && <span className="ml-2 text-destructive font-medium">· {escalatedCount} escalated</span>}
        </p>
      </div>

      <div className="flex flex-col sm:flex-row gap-3">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input placeholder="Search violations..." value={search} onChange={(e) => setSearch(e.target.value)} className="pl-9" />
        </div>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-[160px]">
            <Filter className="h-4 w-4 mr-2" />
            <SelectValue placeholder="All statuses" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Statuses</SelectItem>
            <SelectItem value="open">Open</SelectItem>
            <SelectItem value="pending">Pending</SelectItem>
            <SelectItem value="escalated">Escalated</SelectItem>
            <SelectItem value="resolved">Resolved</SelectItem>
            <SelectItem value="closed">Closed</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {loading ? (
        <div className="flex justify-center py-12"><Loader2 className="h-8 w-8 animate-spin text-primary" /></div>
      ) : filtered.length === 0 ? (
        <Card><CardContent className="py-12 text-center text-muted-foreground">
          <AlertTriangle className="mx-auto h-12 w-12 mb-4 opacity-50" />
          <p>{search || statusFilter !== "all" ? "No violations match your filters." : "No violations found."}</p>
        </CardContent></Card>
      ) : (
        <div className="rounded-lg border bg-card">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Title</TableHead>
                <TableHead>Association</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Priority</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>Stage</TableHead>
                <TableHead>Date</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {filtered.map((v) => (
                <TableRow key={v.id} className="cursor-pointer hover:bg-muted/50" onClick={() => setSelectedViolation(v)}>
                  <TableCell className="font-medium">{v.title}</TableCell>
                  <TableCell>{v.associations?.name ?? "—"}</TableCell>
                  <TableCell className="text-muted-foreground">{v.violation_type || v.category || "—"}</TableCell>
                  <TableCell>{priorityLabel(v.priority)}</TableCell>
                  <TableCell><Badge variant={statusColor(v.status)}>{v.status || "open"}</Badge></TableCell>
                  <TableCell className="text-muted-foreground text-sm">{v.stage || v.notice_level || "—"}</TableCell>
                  <TableCell className="text-muted-foreground">{format(new Date(v.created_at), "MMM d, yyyy")}</TableCell>
                  <TableCell className="text-right">
                    <Button variant="ghost" size="sm" onClick={(e) => { e.stopPropagation(); setSelectedViolation(v); }}>
                      <Eye className="w-4 h-4" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      <ClientViolationDetailDialog
        violation={selectedViolation}
        open={!!selectedViolation}
        onOpenChange={(open) => !open && setSelectedViolation(null)}
      />
    </div>
  );
}
