import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useNavigate } from "react-router-dom";
import { getCardDef } from "./cardRegistry";

interface Props {
  cardId: string;
}

const STAT_CONFIG: Record<string, { table: string; filter?: Record<string, string | string[]>; path: string }> = {
  stat_pending_arc: { table: "arc_applications", filter: { status: "submitted" }, path: "/dashboard/arc-applications" },
  stat_open_violations: { table: "violations", filter: { status: ["open", "escalated", "recommended_for_fining"] }, path: "/dashboard/violations" },
  stat_collections: { table: "units", filter: { status: "delinquent" }, path: "/dashboard/collections" },
  stat_active_owners: { table: "owners", filter: { status: "active" }, path: "/dashboard/owner-roster" },
  stat_open_requests: { table: "client_requests", filter: { status: "open" }, path: "/dashboard/client-requests" },
};

export default function StatWidget({ cardId }: Props) {
  const [count, setCount] = useState<number | null>(null);
  const navigate = useNavigate();
  const def = getCardDef(cardId);
  const config = STAT_CONFIG[cardId];

  useEffect(() => {
    if (!config) return;
    const fetchCount = async () => {
      let query = supabase.from(config.table as any).select("id", { count: "exact", head: true }) as any;
      if (config.filter) {
        Object.entries(config.filter).forEach(([k, v]) => {
          if (Array.isArray(v)) {
            query = query.in(k, v);
          } else {
            query = query.eq(k, v);
          }
        });
      }
      const { count: c } = await query;
      setCount(c ?? 0);
    };
    fetchCount();
  }, [cardId]);

  if (!def || !config) return null;
  const Icon = def.icon;

  return (
    <div
      className="h-full flex flex-col p-6 cursor-pointer"
      onClick={() => navigate(config.path)}
    >
      <div className="flex flex-row items-center justify-between pb-2">
        <span className="text-sm font-medium">{def.title}</span>
        <Icon className="h-4 w-4 text-muted-foreground" />
      </div>
      <div className="text-2xl font-bold">{count ?? "—"}</div>
    </div>
  );
}
