import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent } from "@/components/ui/card";
import { Scale, Search } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";

export default function LegalCasesPage() {
  const [cases, setCases] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const navigate = useNavigate();

  useEffect(() => {
    const fetchCases = async () => {
      setLoading(true);

      const { data: assignedAssociationIds } = await (supabase as any).rpc("get_legal_association_ids");
      const scopedAssociationIds = assignedAssociationIds || [];

      if (scopedAssociationIds.length === 0) {
        setCases([]);
        setLoading(false);
        return;
      }

      const query = supabase
        .from("legal_matters")
        .select("id, title, case_number, created_at, has_payment_plan, is_bankruptcy")
        .eq("current_stage", "sent_to_attorney")
        .eq("status", "open")
        .in("association_id", scopedAssociationIds)
        .order("created_at", { ascending: false });

      const { data: matters, error } = await query;

      if (error) {
        console.error("Error fetching legal cases:", error);
        setLoading(false);
        return;
      }

      setCases(matters || []);
      setLoading(false);
    };

    fetchCases();
  }, []);

  const filtered = cases.filter((c) => {
    const q = search.toLowerCase();
    return (
      c.title?.toLowerCase().includes(q) ||
      c.case_number?.toLowerCase().includes(q)
    );
  });

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Scale className="h-6 w-6 text-primary" />
          <div>
            <h1 className="text-xl font-bold text-foreground">Attorney Cases</h1>
            <p className="text-sm text-muted-foreground">Properties referred to legal counsel</p>
          </div>
        </div>
        <div className="relative w-64">
          <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Search cases..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-8 h-9 text-sm"
          />
        </div>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-20">
          <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />
        </div>
      ) : filtered.length === 0 ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-16 text-muted-foreground">
            <Scale className="h-10 w-10 mb-3 opacity-30" />
            <p className="text-sm">No cases currently referred to attorney.</p>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-3">
          {filtered.map((matter) => (
            <Card
              key={matter.id}
              className="cursor-pointer hover:shadow-md transition-shadow border-border"
              onClick={() => navigate(`/legal/case/${matter.id}`)}
            >
              <CardContent className="p-4">
                <div className="flex items-center justify-between gap-4">
                  <h3 className="flex-1 truncate text-sm font-semibold text-foreground">{matter.title}</h3>
                  {matter.has_payment_plan && <Badge variant="secondary" className="shrink-0 text-xs">Payment Plan</Badge>}
                  {matter.is_bankruptcy && <Badge variant="destructive" className="shrink-0 text-xs">Bankruptcy</Badge>}
                  {matter.case_number && <span className="text-xs text-muted-foreground">{matter.case_number}</span>}
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
