import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Progress } from "@/components/ui/progress";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { ClipboardCheck, Search, ChevronRight, Loader2 } from "lucide-react";
import { getDefaultComplianceTemplate, type ChecklistSection } from "@/data/complianceChecklistTemplate";

type Row = {
  id: string;
  name: string;
  done: number;
  total: number;
  hasRecord: boolean;
};

function countItems(items: ChecklistSection[]) {
  let total = 0, done = 0;
  for (const s of items || []) {
    for (const c of s.categories || []) {
      for (const i of c.items || []) {
        total++;
        if (i.done) done++;
      }
    }
  }
  return { total, done };
}

export default function ComplianceChecklistsHubPage() {
  const navigate = useNavigate();
  const currentYear = new Date().getFullYear();
  const [fiscalYear, setFiscalYear] = useState(currentYear);
  const [rows, setRows] = useState<Row[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");

  const years = Array.from({ length: 5 }, (_, i) => currentYear - 2 + i);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      setLoading(true);
      const { data: assocs } = await supabase
        .from("associations")
        .select("id, name")
        .eq("status", "active")
        .order("name");

      const ids = (assocs || []).map(a => a.id);
      const { data: checklists } = ids.length
        ? await supabase
            .from("compliance_checklists")
            .select("association_id, items")
            .eq("fiscal_year", fiscalYear)
            .in("association_id", ids)
        : { data: [] as any[] };

      const byAssoc = new Map<string, any>();
      (checklists || []).forEach((c: any) => byAssoc.set(c.association_id, c.items));

      const defaultTotal = countItems(getDefaultComplianceTemplate()).total;

      const next: Row[] = (assocs || []).map((a: any) => {
        const items = byAssoc.get(a.id);
        if (items) {
          const { total, done } = countItems(items as ChecklistSection[]);
          return { id: a.id, name: a.name, total, done, hasRecord: true };
        }
        return { id: a.id, name: a.name, total: defaultTotal, done: 0, hasRecord: false };
      });

      if (!cancelled) {
        setRows(next);
        setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [fiscalYear]);

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase();
    if (!q) return rows;
    return rows.filter(r => r.name.toLowerCase().includes(q));
  }, [rows, search]);

  const totals = useMemo(() => {
    const total = rows.reduce((s, r) => s + r.total, 0);
    const done = rows.reduce((s, r) => s + r.done, 0);
    const pct = total > 0 ? Math.round((done / total) * 100) : 0;
    const completed = rows.filter(r => r.total > 0 && r.done === r.total).length;
    return { total, done, pct, completed };
  }, [rows]);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div>
          <h1 className="text-2xl font-bold text-foreground flex items-center gap-2">
            <ClipboardCheck className="h-6 w-6 text-primary" /> Compliance Checklists
          </h1>
          <p className="text-sm text-muted-foreground mt-1">
            Central view of every association's compliance checklist for the selected fiscal year.
          </p>
        </div>
        <Select value={String(fiscalYear)} onValueChange={(v) => setFiscalYear(Number(v))}>
          <SelectTrigger className="w-[140px]">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {years.map(y => <SelectItem key={y} value={String(y)}>FY {y}</SelectItem>)}
          </SelectContent>
        </Select>
      </div>

      {/* Summary */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
        <Card><CardContent className="py-4">
          <p className="text-xs text-muted-foreground">Associations</p>
          <p className="text-2xl font-bold text-foreground">{rows.length}</p>
        </CardContent></Card>
        <Card><CardContent className="py-4">
          <p className="text-xs text-muted-foreground">Fully Compliant</p>
          <p className="text-2xl font-bold text-foreground">{totals.completed}</p>
        </CardContent></Card>
        <Card><CardContent className="py-4">
          <p className="text-xs text-muted-foreground">Items Completed</p>
          <p className="text-2xl font-bold text-foreground">{totals.done} / {totals.total}</p>
        </CardContent></Card>
        <Card><CardContent className="py-4">
          <p className="text-xs text-muted-foreground">Overall Progress</p>
          <div className="flex items-center gap-2 mt-1">
            <Progress value={totals.pct} className="h-2 flex-1" />
            <span className="text-sm font-medium text-foreground">{totals.pct}%</span>
          </div>
        </CardContent></Card>
      </div>

      {/* Search */}
      <div className="relative max-w-md">
        <Search className="h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
        <Input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search associations..."
          className="pl-9"
        />
      </div>

      {/* List */}
      {loading ? (
        <div className="flex items-center justify-center py-24">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
        </div>
      ) : filtered.length === 0 ? (
        <Card>
          <CardContent className="py-12 text-center text-muted-foreground">
            No associations found.
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-2">
          {filtered.map((r) => {
            const pct = r.total > 0 ? Math.round((r.done / r.total) * 100) : 0;
            const complete = r.total > 0 && r.done === r.total;
            return (
              <Card
                key={r.id}
                className="cursor-pointer hover:border-primary transition-colors"
                onClick={() => navigate(`/dashboard/associations/${r.id}/compliance`)}
              >
                <CardContent className="py-3 px-4">
                  <div className="flex items-center gap-4">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <p className="font-medium text-foreground truncate">{r.name}</p>
                        {complete && (
                          <span className="text-xs text-primary font-medium">✓ Complete</span>
                        )}
                        {!r.hasRecord && (
                          <span className="text-xs text-muted-foreground">(not started)</span>
                        )}
                      </div>
                      <div className="flex items-center gap-3 mt-1">
                        <Progress value={pct} className="h-2 flex-1 max-w-md" />
                        <span className="text-xs text-muted-foreground whitespace-nowrap">
                          {r.done}/{r.total} ({pct}%)
                        </span>
                      </div>
                    </div>
                    <Button variant="ghost" size="sm">
                      Open <ChevronRight className="h-4 w-4 ml-1" />
                    </Button>
                  </div>
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}
