import { useState, useEffect } from "react";
import { api } from "@/services/api";
import { Apple, Zap, Dumbbell, Wheat } from "lucide-react";

const STANDAR = { kalori: 700, protein: 20, karbo: 100, lemak: 25 };

export default function TabGizi({ sppgId }) {
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [filterMinggu, setFilterMinggu] = useState("Semua");

  useEffect(() => {
    api.filter("BahanMakanan", { sppg_id: sppgId }).then((data) => {
      setList(data);
      setLoading(false);
    });
  }, [sppgId]);

  const mingguList = [...new Set(list.map((b) => b.minggu_ke).filter(Boolean))].sort();
  const filtered = filterMinggu === "Semua" ? list : list.filter((b) => String(b.minggu_ke) === filterMinggu);

  const totalKalori = filtered.reduce((acc, b) => acc + ((b.kalori_per_100g || 0) * (b.jumlah || 0) * 10), 0);
  const totalProtein = filtered.reduce((acc, b) => acc + ((b.protein_per_100g || 0) * (b.jumlah || 0) * 10), 0);
  const totalKarbo = filtered.reduce((acc, b) => acc + ((b.karbo_per_100g || 0) * (b.jumlah || 0) * 10), 0);

  const GiziCard = ({ icon: Icon, label, value, satuan, standar, color }) => {
    const pct = Math.min((value / standar) * 100, 100);
    const ok = pct >= 80 && pct <= 120;
    return (
      <div className="bg-card rounded-xl border border-border p-5">
        <div className="flex items-center gap-3 mb-3">
          <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${color}`}>
            <Icon className="w-5 h-5 text-white" />
          </div>
          <div>
            <p className="text-xs text-muted-foreground">{label}</p>
            <p className="text-xl font-black text-foreground">{value.toFixed(0)} <span className="text-sm font-normal">{satuan}</span></p>
          </div>
        </div>
        <div className="w-full bg-muted rounded-full h-2 mb-1">
          <div className={`h-2 rounded-full transition-all ${ok ? "bg-emerald-500" : pct < 80 ? "bg-amber-500" : "bg-red-500"}`} style={{ width: `${pct}%` }} />
        </div>
        <p className={`text-xs font-medium ${ok ? "text-emerald-600" : "text-amber-600"}`}>
          Standar: {standar} {satuan} — {ok ? "✓ Optimal" : pct < 80 ? "⚠ Kurang" : "⚠ Berlebih"}
        </p>
      </div>
    );
  };

  const byDate = [...new Map(filtered.map((b) => [b.tanggal, b.tanggal])).keys()].sort().reverse();

  return (
    <div className="space-y-5">
      <div className="flex flex-wrap gap-2">
        <button onClick={() => setFilterMinggu("Semua")} className={`px-3 py-1.5 rounded-full text-xs font-semibold ${filterMinggu === "Semua" ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}>Semua</button>
        {mingguList.map((m) => (
          <button key={m} onClick={() => setFilterMinggu(String(m))} className={`px-3 py-1.5 rounded-full text-xs font-semibold ${filterMinggu === String(m) ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}>Minggu {m}</button>
        ))}
      </div>

      {loading ? (
        <div className="flex justify-center py-12"><div className="w-6 h-6 border-2 border-primary/20 border-t-primary rounded-full animate-spin" /></div>
      ) : (
        <>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            <GiziCard icon={Zap} label="Total Kalori" value={totalKalori} satuan="kkal" standar={STANDAR.kalori * filtered.length / 7} color="bg-amber-500" />
            <GiziCard icon={Dumbbell} label="Total Protein" value={totalProtein} satuan="gram" standar={STANDAR.protein * filtered.length / 7} color="bg-blue-500" />
            <GiziCard icon={Wheat} label="Total Karbohidrat" value={totalKarbo} satuan="gram" standar={STANDAR.karbo * filtered.length / 7} color="bg-green-500" />
          </div>

          <div className="bg-card rounded-xl border border-border p-5">
            <h4 className="font-bold text-foreground mb-4">Rekap Gizi per Tanggal</h4>
            {byDate.length === 0 ? (
              <p className="text-sm text-muted-foreground text-center py-8">Belum ada data bahan makanan dengan info gizi. Tambahkan nilai kalori/protein/karbo di tab Bahan Makanan.</p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead className="bg-muted/50">
                    <tr>
                      <th className="text-left px-3 py-2 text-xs font-semibold text-muted-foreground">Tanggal</th>
                      <th className="text-right px-3 py-2 text-xs font-semibold text-muted-foreground">Kalori (kkal)</th>
                      <th className="text-right px-3 py-2 text-xs font-semibold text-muted-foreground">Protein (g)</th>
                      <th className="text-right px-3 py-2 text-xs font-semibold text-muted-foreground">Karbo (g)</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border">
                    {byDate.map((tgl) => {
                      const items = filtered.filter((b) => b.tanggal === tgl);
                      const kal = items.reduce((a, b) => a + ((b.kalori_per_100g || 0) * (b.jumlah || 0) * 10), 0);
                      const prot = items.reduce((a, b) => a + ((b.protein_per_100g || 0) * (b.jumlah || 0) * 10), 0);
                      const karbo = items.reduce((a, b) => a + ((b.karbo_per_100g || 0) * (b.jumlah || 0) * 10), 0);
                      return (
                        <tr key={tgl} className="hover:bg-muted/30">
                          <td className="px-3 py-2 font-medium">{tgl}</td>
                          <td className="px-3 py-2 text-right">{kal.toFixed(0)}</td>
                          <td className="px-3 py-2 text-right">{prot.toFixed(1)}</td>
                          <td className="px-3 py-2 text-right">{karbo.toFixed(1)}</td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
}