"use client"; import { useEffect, useState } from "react"; import { CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { DashboardCard } from "@/components/dashboard-card"; const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL ?? "http://localhost:4000"; const LABELS = [ "SANGAT TINGGI", "TINGGI", "SEDANG", "RENDAH", "TIDAK PRIORITAS", ] as const; const LABEL_STYLES: Record = { "SANGAT TINGGI": { bar: "bg-red-500", text: "text-red-700", dot: "bg-red-500" }, "TINGGI": { bar: "bg-orange-500", text: "text-orange-700", dot: "bg-orange-500" }, "SEDANG": { bar: "bg-amber-500", text: "text-amber-700", dot: "bg-amber-500" }, "RENDAH": { bar: "bg-emerald-500", text: "text-emerald-700", dot: "bg-emerald-500" }, "TIDAK PRIORITAS": { bar: "bg-blue-500", text: "text-blue-700", dot: "bg-blue-500" }, }; export function FuzzyPriorityStats({ refreshKey, onRecomputed, }: { refreshKey?: number; onRecomputed?: () => void; }) { const [stats, setStats] = useState | null>(null); const [recomputing, setRecomputing] = useState(false); const [recomputeMsg, setRecomputeMsg] = useState(null); useEffect(() => { fetch(`${BACKEND_URL}/households/stats-fuzzy`) .then((r) => r.json()) .then(setStats) .catch(() => setStats(null)); }, [refreshKey]); async function handleRecompute() { setRecomputing(true); setRecomputeMsg(null); try { const token = localStorage.getItem("auth_token"); const res = await fetch(`${BACKEND_URL}/households/recompute-fuzzy`, { method: "POST", headers: token ? { Authorization: `Bearer ${token}` } : {}, }); if (!res.ok) { const data = await res.json().catch(() => ({})); throw new Error(data.error ?? "Gagal menghitung ulang"); } const data = await res.json(); setRecomputeMsg(`${data.updated} dari ${data.total} warga dihitung ulang`); onRecomputed?.(); } catch (err) { setRecomputeMsg(err instanceof Error ? err.message : "Terjadi kesalahan"); } finally { setRecomputing(false); } } if (!stats) return null; const total = LABELS.reduce((sum, l) => sum + (stats[l] ?? 0), 0); if (total === 0) return null; return (
Distribusi Prioritas Fuzzy {recomputeMsg ?? `${total} warga teranalisis oleh sistem fuzzy`}
{LABELS.map((label) => { const count = stats[label] ?? 0; const pct = total > 0 ? Math.round((count / total) * 100) : 0; const style = LABEL_STYLES[label]; return (
{label}
{count}
{pct}%
); })}
); }