import { AlertTriangle, TrendingUp, Wallet, X } from "lucide-react";
import { useState } from "react";

// Detect anomalies from SPPG list
export function detectAnomalies(sppgList) {
  const anomalies = [];
  if (!sppgList.length) return anomalies;

  const avgCostPerOmprengan = sppgList
    .filter((s) => s.jumlah_omprengan > 0)
    .reduce((acc, s) => acc + (s.dana_dibelanjakan || 0) / s.jumlah_omprengan, 0) /
    (sppgList.filter((s) => s.jumlah_omprengan > 0).length || 1);

  sppgList.forEach((s) => {
    // Overspending
    if ((s.dana_dibelanjakan || 0) > (s.dana_diterima || 0) && s.dana_diterima > 0) {
      anomalies.push({
        sppg: s.nama,
        type: "danger",
        msg: `Dana dibelanjakan melebihi dana diterima (defisit Rp ${((s.dana_dibelanjakan - s.dana_diterima) / 1000000).toFixed(1)}jt)`,
        icon: Wallet,
      });
    }
    // Cost per omprengan too high (>2x average)
    if (s.jumlah_omprengan > 0 && avgCostPerOmprengan > 0) {
      const costPer = (s.dana_dibelanjakan || 0) / s.jumlah_omprengan;
      if (costPer > avgCostPerOmprengan * 2) {
        anomalies.push({
          sppg: s.nama,
          type: "warning",
          msg: `Biaya per omprengan ${(costPer / 1000).toFixed(0)}rb — 2x di atas rata-rata nasional`,
          icon: TrendingUp,
        });
      }
      // Cost suspiciously low (<30% average) — possible under-reporting
      if (costPer < avgCostPerOmprengan * 0.3 && costPer > 0) {
        anomalies.push({
          sppg: s.nama,
          type: "warning",
          msg: `Biaya per omprengan sangat rendah (${(costPer / 1000).toFixed(0)}rb) — perlu verifikasi`,
          icon: AlertTriangle,
        });
      }
    }
  });

  return anomalies;
}

export default function AnomalyAlert({ sppgList = [] }) {
  const [dismissed, setDismissed] = useState([]);
  const anomalies = detectAnomalies(sppgList).filter((_, i) => !dismissed.includes(i));
  if (!anomalies.length) return null;

  return (
    <div className="space-y-2">
      <div className="flex items-center gap-2 mb-1">
        <AlertTriangle className="w-4 h-4 text-red-500" />
        <span className="text-sm font-bold text-red-600">{anomalies.length} Anomali Terdeteksi</span>
      </div>
      {anomalies.map((a, i) => (
        <div
          key={i}
          className={`flex items-start gap-3 rounded-xl px-4 py-3 border ${
            a.type === "danger"
              ? "bg-red-50 border-red-200"
              : "bg-amber-50 border-amber-200"
          }`}
        >
          <a.icon className={`w-4 h-4 mt-0.5 flex-shrink-0 ${a.type === "danger" ? "text-red-500" : "text-amber-500"}`} />
          <div className="flex-1 min-w-0">
            <p className={`text-xs font-bold ${a.type === "danger" ? "text-red-700" : "text-amber-700"}`}>{a.sppg}</p>
            <p className={`text-xs ${a.type === "danger" ? "text-red-600" : "text-amber-600"}`}>{a.msg}</p>
          </div>
          <button onClick={() => setDismissed((prev) => [...prev, i])} className="flex-shrink-0 opacity-50 hover:opacity-100">
            <X className="w-3.5 h-3.5" />
          </button>
        </div>
      ))}
    </div>
  );
}