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, Trash2, Edit2, Save, X, ShoppingCart } from "lucide-react";
import { toast } from "sonner";

const formatRp = (n) => `Rp ${(n || 0).toLocaleString("id-ID")}`;
const KATEGORI = ["Karbohidrat", "Protein Hewani", "Protein Nabati", "Sayuran", "Buah", "Bumbu", "Minyak & Lemak", "Lainnya"];

const emptyForm = { nama_bahan: "", kategori: "", satuan: "", jumlah: "", harga_satuan: "", supplier: "", tanggal: new Date().toISOString().slice(0, 10), minggu_ke: "" };

export default function TabBahanMakanan({ 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 [filterMinggu, setFilterMinggu] = useState("Semua");

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

  const load = async () => {
    const data = await api.filter("BahanMakanan", { sppg_id: sppgId });
    setList(data);
    setLoading(false);
  };

  const handleSubmit = async () => {
    if (!form.nama_bahan || !form.kategori) return toast.error("Nama bahan dan kategori wajib diisi");
    const total = Number(form.jumlah) * Number(form.harga_satuan);
    const payload = { ...form, sppg_id: sppgId, jumlah: Number(form.jumlah), harga_satuan: Number(form.harga_satuan), total_harga: total, minggu_ke: Number(form.minggu_ke) };
    if (editId) { await api.update("BahanMakanan", editId, payload); toast.success("Diperbarui"); }
    else { await api.create("BahanMakanan", payload); toast.success("Bahan ditambahkan"); }
    setShowForm(false); setEditId(null); setForm(emptyForm); load();
  };

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

  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 totalPembelian = filtered.reduce((acc, b) => acc + (b.total_harga || 0), 0);

  const byKategori = KATEGORI.map((k) => ({ kategori: k, total: filtered.filter((b) => b.kategori === k).reduce((a, b) => a + (b.total_harga || 0), 0) })).filter((k) => k.total > 0);

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        <div className="bg-card rounded-xl border border-border p-4 col-span-2 sm:col-span-1">
          <p className="text-xs text-muted-foreground">Total Pembelian</p>
          <p className="text-lg font-black text-primary">{formatRp(totalPembelian)}</p>
        </div>
        {byKategori.slice(0, 3).map((k) => (
          <div key={k.kategori} className="bg-card rounded-xl border border-border p-4">
            <p className="text-xs text-muted-foreground">{k.kategori}</p>
            <p className="text-sm font-bold text-foreground">{formatRp(k.total)}</p>
          </div>
        ))}
      </div>

      <div className="flex items-center justify-between gap-3 flex-wrap">
        <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 Minggu</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>
        <Button size="sm" onClick={() => { setShowForm(true); setEditId(null); setForm(emptyForm); }}>
          <Plus className="w-3.5 h-3.5 mr-1" />Tambah Bahan
        </Button>
      </div>

      {showForm && (
        <div className="bg-card rounded-xl border border-border p-5 space-y-4">
          <h4 className="font-bold">{editId ? "Edit Bahan" : "Tambah Bahan Makanan"}</h4>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            <div><label className="text-xs font-medium mb-1 block">Nama Bahan *</label><Input value={form.nama_bahan} onChange={(e) => setForm({ ...form, nama_bahan: e.target.value })} placeholder="Nama bahan" /></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.map((k) => <SelectItem key={k} value={k}>{k}</SelectItem>)}</SelectContent>
              </Select>
            </div>
            <div><label className="text-xs font-medium mb-1 block">Satuan</label><Input value={form.satuan} onChange={(e) => setForm({ ...form, satuan: e.target.value })} placeholder="kg / liter / pcs" /></div>
            <div><label className="text-xs font-medium mb-1 block">Jumlah</label><Input type="number" value={form.jumlah} onChange={(e) => setForm({ ...form, jumlah: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">Harga Satuan (Rp)</label><Input type="number" value={form.harga_satuan} onChange={(e) => setForm({ ...form, harga_satuan: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">Total: {formatRp(Number(form.jumlah) * Number(form.harga_satuan))}</label></div>
            <div><label className="text-xs font-medium mb-1 block">Supplier</label><Input value={form.supplier} onChange={(e) => setForm({ ...form, supplier: e.target.value })} placeholder="Nama supplier" /></div>
            <div><label className="text-xs font-medium mb-1 block">Tanggal Pembelian</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">Minggu Ke-</label><Input type="number" value={form.minggu_ke} onChange={(e) => setForm({ ...form, minggu_ke: e.target.value })} placeholder="1" /></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 bahan makanan.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-muted/50">
                <tr>{["Tanggal", "Nama Bahan", "Kategori", "Jumlah", "Harga Satuan", "Total", "Supplier", "Aksi"].map((h) => (
                  <th key={h} className="text-left px-3 py-3 text-xs font-semibold text-muted-foreground">{h}</th>
                ))}</tr>
              </thead>
              <tbody className="divide-y divide-border">
                {filtered.map((b) => (
                  <tr key={b.id} className="hover:bg-muted/30">
                    <td className="px-3 py-3 text-muted-foreground">{b.tanggal}</td>
                    <td className="px-3 py-3 font-medium">{b.nama_bahan}</td>
                    <td className="px-3 py-3"><span className="px-2 py-0.5 rounded-full text-xs bg-muted text-muted-foreground">{b.kategori}</span></td>
                    <td className="px-3 py-3">{b.jumlah} {b.satuan}</td>
                    <td className="px-3 py-3">{formatRp(b.harga_satuan)}</td>
                    <td className="px-3 py-3 font-semibold text-primary">{formatRp(b.total_harga)}</td>
                    <td className="px-3 py-3 text-muted-foreground">{b.supplier || "-"}</td>
                    <td className="px-3 py-3">
                      <div className="flex gap-1">
                        <Button size="icon" variant="ghost" className="h-7 w-7" onClick={() => handleEdit(b)}><Edit2 className="w-3.5 h-3.5" /></Button>
                        <Button size="icon" variant="ghost" className="h-7 w-7 text-destructive" onClick={() => handleDelete(b.id)}><Trash2 className="w-3.5 h-3.5" /></Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}