import { useState, useEffect } from "react";
import { api } from "@/services/api";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, Save, X, Edit2, Trash2, Flame } from "lucide-react";
import { toast } from "sonner";

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

// Entity BiayaOperasional — kita simpan di Transaksi dengan flag kategori khusus
const KATEGORI_OPS = [
  "Gas LPG",
  "Listrik",
  "Air / PDAM",
  "Sewa Dapur",
  "Peralatan Masak",
  "Plastik & Kemasan",
  "Sabun & Kebersihan",
  "Transportasi Internal",
  "Gaji Karyawan",
  "Lain-lain",
];

const emptyForm = {
  tanggal: new Date().toISOString().slice(0, 10),
  kategori: "",
  deskripsi: "",
  jumlah: "",
};

// Gunakan entity Transaksi dengan field supplier = "OPERASIONAL_DAPUR" sebagai penanda
export default function TabOperasionalDapur({ sppgId }) {
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [editId, setEditId] = useState(null);
  const [form, setForm] = useState(emptyForm);
  const [filterBulan, setFilterBulan] = useState("Semua");

  useEffect(() => { load(); }, [sppgId]);

  const load = async () => {
    // filter by supplier = "OPERASIONAL_DAPUR" sebagai identifier
    const data = await api.filter("Transaksi", { sppg_id: sppgId);
    setList(data);
    setLoading(false);
  };

  const handleSubmit = async () => {
    if (!form.kategori || !form.jumlah) return toast.error("Kategori dan jumlah wajib diisi");
    const payload = {
      sppg_id: sppgId,
      tanggal: form.tanggal,
      kategori: form.kategori,
      deskripsi: form.deskripsi,
      jumlah: Number(form.jumlah),
      supplier: "OPERASIONAL_DAPUR",
    };
    if (editId) {
      await api.update("Transaksi", editId, payload);
      toast.success("Diperbarui");
    } else {
      await api.create("Transaksi", payload);
      toast.success("Biaya operasional ditambahkan");
    }
    setShowForm(false); setEditId(null); setForm(emptyForm); load();
  };

  const handleEdit = (item) => { setForm({ tanggal: item.tanggal, kategori: item.kategori, deskripsi: item.deskripsi || "", jumlah: item.jumlah }); setEditId(item.id); setShowForm(true); };
  const handleDelete = async (id) => { await api.remove("Transaksi", id); toast.success("Dihapus"); load(); };

  // Bulan unik dari data
  const bulanList = [...new Set(list.map((b) => b.tanggal?.slice(0, 7)).filter(Boolean))].sort().reverse();
  const filtered = filterBulan === "Semua" ? list : list.filter((b) => b.tanggal?.startsWith(filterBulan));
  const total = filtered.reduce((a, b) => a + (b.jumlah || 0), 0);

  // Ringkasan per kategori
  const byKat = KATEGORI_OPS.map((k) => ({
    k,
    total: filtered.filter((b) => b.kategori === k).reduce((a, b) => a + (b.jumlah || 0), 0),
  })).filter((x) => x.total > 0);

  return (
    <div className="space-y-5">
      {/* Header info */}
      <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
        <p className="text-sm font-bold text-amber-800 flex items-center gap-2"><Flame className="w-4 h-4" />Biaya Operasional Dapur</p>
        <p className="text-xs text-amber-700 mt-1">
          Catat semua pengeluaran operasional di luar bahan makanan — gas, listrik, kemasan, gaji, dll. Dana MBG dialokasikan sebagian untuk biaya operasional ini.
        </p>
      </div>

      {/* Summary */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        <div className="bg-primary/5 rounded-xl border border-primary/20 p-4 col-span-2 sm:col-span-1">
          <p className="text-xs text-muted-foreground">Total Operasional</p>
          <p className="text-lg font-black text-primary">{formatRp(total)}</p>
        </div>
        {byKat.slice(0, 3).map((x) => (
          <div key={x.k} className="bg-card rounded-xl border border-border p-4">
            <p className="text-xs text-muted-foreground truncate">{x.k}</p>
            <p className="text-sm font-bold text-foreground">{formatRp(x.total)}</p>
          </div>
        ))}
      </div>

      {/* Grafik mini per kategori */}
      {byKat.length > 0 && (
        <div className="bg-card rounded-xl border border-border p-4">
          <p className="text-xs font-semibold text-muted-foreground mb-3 uppercase tracking-wide">Distribusi Pengeluaran</p>
          <div className="space-y-2">
            {byKat.sort((a, b) => b.total - a.total).map((x) => (
              <div key={x.k} className="flex items-center gap-3">
                <p className="text-xs text-muted-foreground w-36 truncate flex-shrink-0">{x.k}</p>
                <div className="flex-1 bg-muted rounded-full h-2 overflow-hidden">
                  <div
                    className="h-full bg-primary rounded-full transition-all"
                    style={{ width: `${total > 0 ? (x.total / total) * 100 : 0}%` }}
                  />
                </div>
                <p className="text-xs font-semibold text-foreground w-24 text-right">{formatRp(x.total)}</p>
              </div>
            ))}
          </div>
        </div>
      )}

      <div className="flex items-center justify-between flex-wrap gap-3">
        <div className="flex flex-wrap gap-2">
          <button onClick={() => setFilterBulan("Semua")} className={`px-3 py-1.5 rounded-full text-xs font-semibold ${filterBulan === "Semua" ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}>Semua</button>
          {bulanList.map((b) => (
            <button key={b} onClick={() => setFilterBulan(b)} className={`px-3 py-1.5 rounded-full text-xs font-semibold ${filterBulan === b ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}>{b}</button>
          ))}
        </div>
        <Button size="sm" onClick={() => { setShowForm(true); setEditId(null); setForm(emptyForm); }}>
          <Plus className="w-3.5 h-3.5 mr-1" />Tambah Biaya
        </Button>
      </div>

      {showForm && (
        <div className="bg-card rounded-xl border border-border p-5 space-y-4">
          <h4 className="font-bold">{editId ? "Edit Biaya" : "Catat Biaya Operasional Dapur"}</h4>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            <div>
              <label className="text-xs font-medium mb-1 block">Tanggal</label>
              <Input type="date" value={form.tanggal} onChange={(e) => setForm({ ...form, tanggal: e.target.value })} />
            </div>
            <div>
              <label className="text-xs font-medium mb-1 block">Kategori *</label>
              <Select value={form.kategori} onValueChange={(v) => setForm({ ...form, kategori: v })}>
                <SelectTrigger><SelectValue placeholder="Pilih kategori" /></SelectTrigger>
                <SelectContent>{KATEGORI_OPS.map((k) => <SelectItem key={k} value={k}>{k}</SelectItem>)}</SelectContent>
              </Select>
            </div>
            <div>
              <label className="text-xs font-medium mb-1 block">Keterangan</label>
              <Input value={form.deskripsi} onChange={(e) => setForm({ ...form, deskripsi: e.target.value })} placeholder="Contoh: Gas 12kg Pertamina" />
            </div>
            <div>
              <label className="text-xs font-medium mb-1 block">Jumlah (Rp) *</label>
              <Input type="number" value={form.jumlah} onChange={(e) => setForm({ ...form, jumlah: e.target.value })} placeholder="0" />
            </div>
          </div>
          <div className="flex gap-2">
            <Button size="sm" onClick={handleSubmit}><Save className="w-3.5 h-3.5 mr-1" />Simpan</Button>
            <Button size="sm" variant="outline" onClick={() => { setShowForm(false); setEditId(null); }}><X className="w-3.5 h-3.5 mr-1" />Batal</Button>
          </div>
        </div>
      )}

      <div className="bg-card rounded-xl border border-border overflow-hidden">
        {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>
        ) : filtered.length === 0 ? (
          <div className="text-center py-12 text-sm text-muted-foreground">Belum ada data biaya operasional.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-muted/50">
                <tr>
                  {["Tanggal", "Kategori", "Keterangan", "Jumlah", "Aksi"].map((h) => (
                    <th key={h} className="text-left px-4 py-3 text-xs font-semibold text-muted-foreground">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-border">
                {filtered.map((item) => (
                  <tr key={item.id} className="hover:bg-muted/30">
                    <td className="px-4 py-3 text-muted-foreground">{item.tanggal}</td>
                    <td className="px-4 py-3">
                      <span className="px-2 py-0.5 rounded-full text-xs bg-amber-100 text-amber-700 font-semibold">{item.kategori}</span>
                    </td>
                    <td className="px-4 py-3 text-muted-foreground">{item.deskripsi || "-"}</td>
                    <td className="px-4 py-3 font-bold text-primary">{formatRp(item.jumlah)}</td>
                    <td className="px-4 py-3">
                      <div className="flex gap-1">
                        <Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => handleEdit(item)}><Edit2 className="w-3.5 h-3.5" /></Button>
                        <Button size="icon" variant="ghost" className="h-7 w-7 text-destructive" onClick={() => handleDelete(item.id)}><Trash2 className="w-3.5 h-3.5" /></Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}