import { useState, useEffect } from "react";
import { api } from "@/services/api";
import { ChefHat, Truck, Package, Droplets, UtensilsCrossed, Scale, TrendingUp } from "lucide-react";

const formatRp = (n) => `Rp ${(n || 0).toLocaleString("id-ID")}`;

export default function TabOperasional({ sppgId }) {
  const [karyawan, setKaryawan] = useState([]);
  const [laporan, setLaporan] = useState([]);
  const [omprengan, setOmprengan] = useState([]);
  const [dana, setDana] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    Promise.all([
      api.filter("Karyawan", { sppg_id: sppgId }),
      api.filter("LaporanHarian", { sppg_id: sppgId }),
      api.filter("DataOmprengan", { sppg_id: sppgId }),
      api.filter("RekapDana", { sppg_id: sppgId }),
    ]).then(([k, l, o, d]) => {
      setKaryawan(k); setLaporan(l); setOmprengan(o); setDana(d);
      setLoading(false);
    });
  }, [sppgId]);

  const jabatanStats = [
    { label: "Kepala Koki", icon: ChefHat, color: "bg-amber-100 text-amber-600", count: karyawan.filter((k) => k.jabatan === "Kepala Koki").length },
    { label: "Anggota Koki", icon: UtensilsCrossed, color: "bg-orange-100 text-orange-600", count: karyawan.filter((k) => k.jabatan === "Anggota Koki").length },
    { label: "Tukang Packing", icon: Package, color: "bg-purple-100 text-purple-600", count: karyawan.filter((k) => k.jabatan === "Tukang Packing").length },
    { label: "Cuci Ompreng", icon: Droplets, color: "bg-teal-100 text-teal-600", count: karyawan.filter((k) => k.jabatan === "Cuci Ompreng").length },
    { label: "Supir", icon: Truck, color: "bg-blue-100 text-blue-600", count: karyawan.filter((k) => k.jabatan === "Supir").length },
    { label: "Ahli Gizi", icon: Scale, color: "bg-green-100 text-green-600", count: karyawan.filter((k) => k.jabatan === "Ahli Gizi").length },
  ];

  const totalOmpreng = omprengan.reduce((a, o) => a + (o.jumlah_omprengan || 0), 0);
  const totalGaji = karyawan.reduce((a, k) => a + (k.gaji || 0), 0);
  const laporanDikirim = laporan.filter((l) => l.status === "Dikirim" || l.status === "Divalidasi").length;
  const lastDana = dana[0];

  if (loading) return <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>;

  return (
    <div className="space-y-6">
      <div className="bg-card rounded-xl border border-border p-5">
        <h3 className="font-bold text-foreground mb-4 flex items-center gap-2"><TrendingUp className="w-4 h-4 text-primary" />Ringkasan Operasional Dapur</h3>
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
          <div className="bg-blue-50 rounded-xl p-4 text-center">
            <p className="text-3xl font-black text-blue-600">{karyawan.filter((k) => k.status === "Aktif").length}</p>
            <p className="text-xs text-muted-foreground mt-1">Karyawan Aktif</p>
          </div>
          <div className="bg-emerald-50 rounded-xl p-4 text-center">
            <p className="text-3xl font-black text-emerald-600">{laporanDikirim}</p>
            <p className="text-xs text-muted-foreground mt-1">Laporan Terkirim</p>
          </div>
          <div className="bg-amber-50 rounded-xl p-4 text-center">
            <p className="text-3xl font-black text-amber-600">{totalOmpreng.toLocaleString()}</p>
            <p className="text-xs text-muted-foreground mt-1">Total Omprengan</p>
          </div>
          <div className="bg-purple-50 rounded-xl p-4 text-center">
            <p className="text-lg font-black text-purple-600">{formatRp(totalGaji)}</p>
            <p className="text-xs text-muted-foreground mt-1">Total Gaji/Bulan</p>
          </div>
        </div>
      </div>

      <div className="bg-card rounded-xl border border-border p-5">
        <h3 className="font-bold text-foreground mb-4">Komposisi Tim Dapur</h3>
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
          {jabatanStats.map((j) => (
            <div key={j.label} className={`rounded-xl p-4 text-center ${j.color.replace("text-", "bg-").replace("-600", "-50")}`}>
              <div className={`w-10 h-10 rounded-full mx-auto mb-2 flex items-center justify-center ${j.color.replace("text-", "bg-").replace("-600", "-100")}`}>
                <j.icon className={`w-5 h-5 ${j.color.split(" ")[1]}`} />
              </div>
              <p className="text-2xl font-black text-foreground">{j.count}</p>
              <p className="text-xs text-muted-foreground mt-0.5">{j.label}</p>
            </div>
          ))}
        </div>
      </div>

      {lastDana && (
        <div className="bg-card rounded-xl border border-border p-5">
          <h3 className="font-bold text-foreground mb-4">Rekap Dana Terakhir ({lastDana.periode})</h3>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
            <div className="bg-emerald-50 rounded-xl p-3">
              <p className="text-xs text-muted-foreground">Dana Masuk</p>
              <p className="font-black text-emerald-600 text-sm">{formatRp(lastDana.total_dana_masuk)}</p>
            </div>
            <div className="bg-red-50 rounded-xl p-3">
              <p className="text-xs text-muted-foreground">Total Keluar</p>
              <p className="font-black text-red-600 text-sm">{formatRp(lastDana.total_pengeluaran)}</p>
            </div>
            <div className={`${(lastDana.sisa_dana || 0) >= 0 ? "bg-blue-50" : "bg-red-50"} rounded-xl p-3`}>
              <p className="text-xs text-muted-foreground">Sisa Dana</p>
              <p className={`font-black text-sm ${(lastDana.sisa_dana || 0) >= 0 ? "text-blue-600" : "text-red-600"}`}>{formatRp(lastDana.sisa_dana)}</p>
            </div>
            <div className="bg-amber-50 rounded-xl p-3">
              <p className="text-xs text-muted-foreground">Biaya/Omprengan</p>
              <p className="font-black text-amber-600 text-sm">{formatRp(lastDana.biaya_per_omprengan)}</p>
            </div>
          </div>
        </div>
      )}

      <div className="bg-card rounded-xl border border-border p-5">
        <h3 className="font-bold text-foreground mb-4">Laporan Terbaru</h3>
        {laporan.length === 0 ? (
          <p className="text-sm text-muted-foreground">Belum ada laporan.</p>
        ) : (
          <div className="space-y-3">
            {laporan.slice(0, 5).map((l) => (
              <div key={l.id} className="flex items-center justify-between gap-3 py-2 border-b border-border last:border-0">
                <div>
                  <p className="text-sm font-semibold text-foreground">{l.jenis} — {l.tanggal}</p>
                  <p className="text-xs text-muted-foreground">{l.jumlah_omprengan} omprengan · {l.jumlah_terdistribusi} terdistribusi</p>
                </div>
                <span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${l.status === "Divalidasi" ? "bg-emerald-100 text-emerald-700" : l.status === "Dikirim" ? "bg-blue-100 text-blue-700" : "bg-gray-100 text-gray-600"}`}>{l.status}</span>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}