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, TrendingDown, TrendingUp } from "lucide-react";
import { toast } from "sonner";

const formatRp = (n) => `Rp ${(n || 0).toLocaleString("id-ID")}`;
const emptyForm = { periode: "Harian", tanggal_mulai: new Date().toISOString().slice(0, 10), tanggal_akhir: new Date().toISOString().slice(0, 10), total_dana_masuk: "", total_bahan_makanan: "", total_gaji: "", total_operasional: "", total_transportasi: "", jumlah_omprengan: "", catatan: "" };

export default function TabRekapDana({ sppgId }) {
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState(emptyForm);
  const [filterPeriode, setFilterPeriode] = useState("Semua");

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

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

  const totalPengeluaran = () => {
    return ["total_bahan_makanan", "total_gaji", "total_operasional", "total_transportasi"].reduce((acc, f) => acc + Number(form[f] || 0), 0);
  };

  const handleSubmit = async () => {
    const pengeluaran = totalPengeluaran();
    const sisa = Number(form.total_dana_masuk || 0) - pengeluaran;
    const biayaPerOmpreng = form.jumlah_omprengan > 0 ? pengeluaran / Number(form.jumlah_omprengan) : 0;
    const payload = { ...form, sppg_id: sppgId, total_pengeluaran: pengeluaran, sisa_dana: sisa, biaya_per_omprengan: biayaPerOmpreng, total_dana_masuk: Number(form.total_dana_masuk), total_bahan_makanan: Number(form.total_bahan_makanan), total_gaji: Number(form.total_gaji), total_operasional: Number(form.total_operasional), total_transportasi: Number(form.total_transportasi), jumlah_omprengan: Number(form.jumlah_omprengan) };
    await api.create("RekapDana", payload);
    toast.success("Rekap dana berhasil disimpan");
    setShowForm(false); setForm(emptyForm); load();
  };

  const filtered = filterPeriode === "Semua" ? list : list.filter((r) => r.periode === filterPeriode);

  return (
    <div className="space-y-5">
      <div className="flex items-center justify-between flex-wrap gap-3">
        <div className="flex flex-wrap gap-2">
          {["Semua", "Harian", "Mingguan", "Bulanan"].map((p) => (
            <button key={p} onClick={() => setFilterPeriode(p)} className={`px-3 py-1.5 rounded-full text-xs font-semibold ${filterPeriode === p ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}>{p}</button>
          ))}
        </div>
        <Button size="sm" onClick={() => setShowForm(true)}>
          <Plus className="w-3.5 h-3.5 mr-1" />Tambah Rekap Dana
        </Button>
      </div>

      {showForm && (
        <div className="bg-card rounded-xl border border-border p-5 space-y-4">
          <h4 className="font-bold">Input Rekap Dana</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">Periode</label>
              <Select value={form.periode} onValueChange={(v) => setForm({ ...form, periode: v })}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent><SelectItem value="Harian">Harian</SelectItem><SelectItem value="Mingguan">Mingguan</SelectItem><SelectItem value="Bulanan">Bulanan</SelectItem></SelectContent>
              </Select>
            </div>
            <div><label className="text-xs font-medium mb-1 block">Tanggal Mulai</label><Input type="date" value={form.tanggal_mulai} onChange={(e) => setForm({ ...form, tanggal_mulai: e.target.value })} /></div>
            <div><label className="text-xs font-medium mb-1 block">Tanggal Akhir</label><Input type="date" value={form.tanggal_akhir} onChange={(e) => setForm({ ...form, tanggal_akhir: e.target.value })} /></div>
            <div><label className="text-xs font-medium mb-1 block">Dana Masuk (Rp)</label><Input type="number" value={form.total_dana_masuk} onChange={(e) => setForm({ ...form, total_dana_masuk: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">Bahan Makanan (Rp)</label><Input type="number" value={form.total_bahan_makanan} onChange={(e) => setForm({ ...form, total_bahan_makanan: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">Gaji (Rp)</label><Input type="number" value={form.total_gaji} onChange={(e) => setForm({ ...form, total_gaji: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">Operasional (Rp)</label><Input type="number" value={form.total_operasional} onChange={(e) => setForm({ ...form, total_operasional: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">Transportasi (Rp)</label><Input type="number" value={form.total_transportasi} onChange={(e) => setForm({ ...form, total_transportasi: e.target.value })} placeholder="0" /></div>
            <div><label className="text-xs font-medium mb-1 block">Jumlah Omprengan</label><Input type="number" value={form.jumlah_omprengan} onChange={(e) => setForm({ ...form, jumlah_omprengan: e.target.value })} placeholder="0" /></div>
          </div>
          <div className="bg-muted/50 rounded-xl p-4 grid grid-cols-2 gap-3">
            <div><p className="text-xs text-muted-foreground">Total Pengeluaran</p><p className="font-black text-destructive">{formatRp(totalPengeluaran())}</p></div>
            <div><p className="text-xs text-muted-foreground">Sisa Dana</p><p className={`font-black ${Number(form.total_dana_masuk || 0) - totalPengeluaran() >= 0 ? "text-emerald-600" : "text-destructive"}`}>{formatRp(Number(form.total_dana_masuk || 0) - totalPengeluaran())}</p></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)}><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 rekap dana.</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-muted/50">
                <tr>{["Periode", "Tanggal", "Dana Masuk", "Total Keluar", "Bahan Makanan", "Gaji", "Operasional", "Sisa Dana", "Biaya/Ompreng"].map((h) => (
                  <th key={h} className="text-left px-3 py-3 text-xs font-semibold text-muted-foreground whitespace-nowrap">{h}</th>
                ))}</tr>
              </thead>
              <tbody className="divide-y divide-border">
                {filtered.map((r) => (
                  <tr key={r.id} className="hover:bg-muted/30">
                    <td className="px-3 py-3"><span className="px-2 py-0.5 rounded-full text-xs bg-blue-100 text-blue-700">{r.periode}</span></td>
                    <td className="px-3 py-3 text-muted-foreground text-xs">{r.tanggal_mulai} s/d {r.tanggal_akhir}</td>
                    <td className="px-3 py-3 font-semibold text-emerald-600">{formatRp(r.total_dana_masuk)}</td>
                    <td className="px-3 py-3 font-semibold text-destructive">{formatRp(r.total_pengeluaran)}</td>
                    <td className="px-3 py-3">{formatRp(r.total_bahan_makanan)}</td>
                    <td className="px-3 py-3">{formatRp(r.total_gaji)}</td>
                    <td className="px-3 py-3">{formatRp(r.total_operasional)}</td>
                    <td className="px-3 py-3 font-bold"><span className={(r.sisa_dana || 0) >= 0 ? "text-emerald-600" : "text-destructive"}>{formatRp(r.sisa_dana)}</span></td>
                    <td className="px-3 py-3 text-primary font-semibold">{formatRp(r.biaya_per_omprengan)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}