import { useEffect, useState } from "react";
import {
  Download,
  FileText,
  Calendar,
  RefreshCw,
  Plus,
  Trash2,
  Pencil,
  Save,
  X,
  ShieldCheck,
} from "lucide-react";

import { Button } from "@/components/ui/button";
import SectionTitle from "../components/SectionTitle";
import StatCard from "../components/StatCard";

import {
  AreaChart,
  Area,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  BarChart,
  Bar,
} from "recharts";

const LIST_API = "http://localhost/backend/api/transaksi/list.php";
const SUMMARY_API = "http://localhost/backend/api/transaksi/summary.php";
const CREATE_API = "http://localhost/backend/api/transaksi/create.php";
const UPDATE_API = "http://localhost/backend/api/transaksi/update.php";
const DELETE_API = "http://localhost/backend/api/transaksi/delete.php";
const SPPG_API = "http://localhost/backend/api/sppg/list.php";
const REKAP_API = "http://localhost/backend/api/laporan/rekap.php";

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

const formatShortRp = (n) => {
  const value = Number(n) || 0;

  if (value >= 1000000000) {
    return `Rp ${(value / 1000000000).toFixed(1)} M`;
  }

  if (value >= 1000000) {
    return `Rp ${(value / 1000000).toFixed(1)} Jt`;
  }

  return formatRp(value);
};

const defaultRekap = {
  ringkasan: {
    total_sppg: 0,
    total_dana: 0,
    total_siswa: 0,
    total_sekolah: 0,
    total_karyawan: 0,
    total_bahan: 0,
    total_pengaduan: 0,
    total_porsi: 0,
    total_terdistribusi: 0,
    belum_tersalurkan: 0,
  },
  sppg: [],
  pengaduan: [],
  bahan_stok_rendah: [],
  laporan_operasional: [],
};

export default function Laporan() {
  const role = localStorage.getItem("role");
  const isAdmin = role === "admin";
  const isPemerintah = role === "pemerintah";

  const [transaksiList, setTransaksiList] = useState([]);
  const [sppgList, setSppgList] = useState([]);
  const [rekap, setRekap] = useState(defaultRekap);

  const [summary, setSummary] = useState({
    total_pemasukan: 0,
    total_pengeluaran: 0,
    sisa_dana: 0,
    total_transaksi: 0,
  });

  const [form, setForm] = useState({
    sppg_id: "",
    tanggal: "",
    kategori: "",
    deskripsi: "",
    supplier: "",
    jenis: "Pengeluaran",
    jumlah: "",
  });

  const [editId, setEditId] = useState(null);

  const [editForm, setEditForm] = useState({
    sppg_id: "",
    tanggal: "",
    kategori: "",
    deskripsi: "",
    supplier: "",
    jenis: "Pengeluaran",
    jumlah: "",
  });

  const [filterSppg, setFilterSppg] = useState("all");
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [updating, setUpdating] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    loadData();
  }, [filterSppg]);

  const loadData = async () => {
    try {
      setLoading(true);
      setError("");

      const [sppgRes, rekapRes] = await Promise.all([
        fetch(SPPG_API),
        fetch(REKAP_API),
      ]);

      const sppgResult = await sppgRes.json();
      const rekapResult = await rekapRes.json();

      if (sppgResult.success && Array.isArray(sppgResult.data)) {
        setSppgList(sppgResult.data);
      } else {
        setSppgList([]);
      }

      if (rekapResult.success && rekapResult.data) {
        setRekap({
          ...defaultRekap,
          ...rekapResult.data,
          ringkasan: {
            ...defaultRekap.ringkasan,
            ...(rekapResult.data.ringkasan || {}),
          },
        });
      } else {
        setRekap(defaultRekap);
      }

      const query =
        filterSppg !== "all" ? `?sppg_id=${filterSppg}` : "";

      const summaryRes = await fetch(`${SUMMARY_API}${query}`);

      if (!summaryRes.ok) {
        throw new Error(`HTTP Summary ${summaryRes.status}`);
      }

      const summaryResult = await summaryRes.json();

      if (summaryResult.success && summaryResult.data) {
        setSummary(summaryResult.data);
      } else {
        setSummary({
          total_pemasukan: 0,
          total_pengeluaran: 0,
          sisa_dana: 0,
          total_transaksi: 0,
        });
      }

      const listRes = await fetch(`${LIST_API}${query}`);

      if (!listRes.ok) {
        throw new Error(`HTTP List ${listRes.status}`);
      }

      const listResult = await listRes.json();

      if (listResult.success && Array.isArray(listResult.data)) {
        setTransaksiList(listResult.data);
      } else {
        setTransaksiList([]);
      }
    } catch (err) {
      console.error("Gagal mengambil laporan:", err);
      setError("Gagal mengambil data laporan dari server");
      setTransaksiList([]);
      setRekap(defaultRekap);
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e) => {
    const { name, value } = e.target;

    setForm((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (!isAdmin) {
      alert("Akses ditolak. Hanya admin yang dapat menambahkan transaksi.");
      return;
    }

    if (!form.sppg_id || !form.tanggal || !form.kategori || !form.jumlah) {
      alert("Mohon isi SPPG, tanggal, kategori, dan jumlah.");
      return;
    }

    try {
      setSubmitting(true);

      const res = await fetch(CREATE_API, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          sppg_id: Number(form.sppg_id),
          tanggal: form.tanggal,
          kategori: form.kategori,
          deskripsi: form.deskripsi,
          supplier: form.supplier,
          jenis: form.jenis,
          jumlah: Number(form.jumlah) || 0,
        }),
      });

      const result = await res.json();

      if (!result.success) {
        alert(result.message || "Gagal menambahkan transaksi");
        return;
      }

      setForm({
        sppg_id: "",
        tanggal: "",
        kategori: "",
        deskripsi: "",
        supplier: "",
        jenis: "Pengeluaran",
        jumlah: "",
      });

      await loadData();
    } catch (err) {
      console.error("Gagal tambah transaksi:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setSubmitting(false);
    }
  };

  const handleDelete = async (id) => {
    if (!isAdmin) {
      alert("Akses ditolak. Hanya admin yang dapat menghapus transaksi.");
      return;
    }

    const yakin = window.confirm("Yakin ingin menghapus transaksi ini?");

    if (!yakin) return;

    try {
      const res = await fetch(`${DELETE_API}?id=${id}`, {
        method: "DELETE",
      });

      const result = await res.json();

      if (!result.success) {
        alert(result.message || "Gagal menghapus transaksi");
        return;
      }

      await loadData();
    } catch (err) {
      console.error("Gagal hapus transaksi:", err);
      alert("Tidak bisa terhubung ke server");
    }
  };

  const startEdit = (item) => {
    if (!isAdmin) {
      alert("Akses ditolak. Hanya admin yang dapat mengedit transaksi.");
      return;
    }

    setEditId(item.id);

    setEditForm({
      sppg_id: item.sppg_id || "",
      tanggal: item.tanggal || "",
      kategori: item.kategori || "",
      deskripsi: item.deskripsi || "",
      supplier: item.supplier || "",
      jenis: item.jenis || "Pengeluaran",
      jumlah: item.jumlah || "",
    });
  };

  const cancelEdit = () => {
    setEditId(null);

    setEditForm({
      sppg_id: "",
      tanggal: "",
      kategori: "",
      deskripsi: "",
      supplier: "",
      jenis: "Pengeluaran",
      jumlah: "",
    });
  };

  const handleEditChange = (e) => {
    const { name, value } = e.target;

    setEditForm((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleUpdate = async (id) => {
    if (!isAdmin) {
      alert("Akses ditolak. Hanya admin yang dapat memperbarui transaksi.");
      return;
    }

    if (
      !editForm.sppg_id ||
      !editForm.tanggal ||
      !editForm.kategori ||
      !editForm.jumlah
    ) {
      alert("Mohon isi SPPG, tanggal, kategori, dan jumlah.");
      return;
    }

    try {
      setUpdating(true);

      const res = await fetch(`${UPDATE_API}?id=${id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          sppg_id: Number(editForm.sppg_id),
          tanggal: editForm.tanggal,
          kategori: editForm.kategori,
          deskripsi: editForm.deskripsi,
          supplier: editForm.supplier,
          jenis: editForm.jenis,
          jumlah: Number(editForm.jumlah) || 0,
        }),
      });

      const result = await res.json();

      if (!result.success) {
        alert(result.message || "Gagal memperbarui transaksi");
        return;
      }

      cancelEdit();
      await loadData();
    } catch (err) {
      console.error("Gagal update transaksi:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setUpdating(false);
    }
  };

  const handlePrint = () => {
    window.print();
  };

  const exportRekapCSV = () => {
    const headers = [
      "Kategori",
      "Nama/Data",
      "Wilayah/Tanggal",
      "Status/Keterangan",
      "Nilai",
    ];

    const rows = [
      ["Ringkasan", "Total SPPG", "-", "-", rekap.ringkasan.total_sppg],
      ["Ringkasan", "Total Dana", "-", "-", rekap.ringkasan.total_dana],
      ["Ringkasan", "Total Siswa", "-", "-", rekap.ringkasan.total_siswa],
      ["Ringkasan", "Total Sekolah", "-", "-", rekap.ringkasan.total_sekolah],
      ["Ringkasan", "Total Karyawan", "-", "-", rekap.ringkasan.total_karyawan],
      ["Ringkasan", "Total Bahan", "-", "-", rekap.ringkasan.total_bahan],
      ["Ringkasan", "Total Pengaduan", "-", "-", rekap.ringkasan.total_pengaduan],
      ["Ringkasan", "Total Porsi", "-", "-", rekap.ringkasan.total_porsi],
      ["Ringkasan", "Terdistribusi", "-", "-", rekap.ringkasan.total_terdistribusi],
      ["Ringkasan", "Belum Tersalurkan", "-", "-", rekap.ringkasan.belum_tersalurkan],
      ...rekap.sppg.map((item) => [
        "SPPG",
        item.nama || "-",
        `${item.kabupaten || "-"}, ${item.provinsi || "-"}`,
        item.status || "-",
        item.total_dana || 0,
      ]),
      ...rekap.bahan_stok_rendah.map((item) => [
        "Bahan Stok Rendah",
        item.nama_bahan || "-",
        item.tanggal_masuk || "-",
        item.kategori || "-",
        item.stok || 0,
      ]),
      ...rekap.laporan_operasional.map((item) => [
        "Laporan Operasional",
        item.menu_makanan || "-",
        item.tanggal || "-",
        item.status || "-",
        `${item.jumlah_terdistribusi || 0}/${item.jumlah_porsi || 0}`,
      ]),
      ...rekap.pengaduan.map((item) => [
        "Pengaduan",
        item.nama || "-",
        item.created_at || "-",
        item.status || "-",
        item.kategori || "-",
      ]),
    ];

    const csvContent = [headers, ...rows]
      .map((row) =>
        row
          .map((cell) => {
            const value = String(cell).replace(/"/g, '""');
            return `"${value}"`;
          })
          .join(",")
      )
      .join("\n");

    const blob = new Blob([`\uFEFF${csvContent}`], {
      type: "text/csv;charset=utf-8;",
    });

    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");

    link.href = url;
    link.download = "rekap-laporan-mbg.csv";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    URL.revokeObjectURL(url);
  };

  const exportCSV = () => {
    if (transaksiList.length === 0) {
      alert("Belum ada data transaksi untuk diunduh.");
      return;
    }

    const headers = [
      "ID",
      "Tanggal",
      "SPPG",
      "Kategori",
      "Deskripsi",
      "Supplier",
      "Jenis",
      "Jumlah",
    ];

    const rows = transaksiList.map((t) => [
      t.id || "",
      t.tanggal || "",
      t.sppg_nama || "",
      t.kategori || "",
      t.deskripsi || "",
      t.supplier || "",
      t.jenis || "",
      t.jumlah || 0,
    ]);

    const csvContent = [headers, ...rows]
      .map((row) =>
        row
          .map((cell) => {
            const value = String(cell).replace(/"/g, '""');
            return `"${value}"`;
          })
          .join(",")
      )
      .join("\n");

    const blob = new Blob([`\uFEFF${csvContent}`], {
      type: "text/csv;charset=utf-8;",
    });

    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");

    const namaFile =
      filterSppg === "all"
        ? "laporan-transaksi-semua-sppg.csv"
        : `laporan-transaksi-sppg-${filterSppg}.csv`;

    link.href = url;
    link.download = namaFile;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    URL.revokeObjectURL(url);
  };

  const chartBulanan = transaksiList.reduce((acc, item) => {
    const tanggal = item.tanggal || "";
    const bulan = tanggal.slice(0, 7);

    if (!bulan) return acc;

    if (!acc[bulan]) {
      acc[bulan] = {
        bulan,
        pemasukan: 0,
        pengeluaran: 0,
      };
    }

    if (item.jenis === "Pemasukan") {
      acc[bulan].pemasukan += Number(item.jumlah) || 0;
    } else {
      acc[bulan].pengeluaran += Number(item.jumlah) || 0;
    }

    return acc;
  }, {});

  const trendData = Object.values(chartBulanan).sort((a, b) =>
    a.bulan.localeCompare(b.bulan)
  );

  const kategoriDataObj = transaksiList.reduce((acc, item) => {
    const kategori = item.kategori || "Lainnya";

    if (!acc[kategori]) {
      acc[kategori] = {
        kategori,
        jumlah: 0,
      };
    }

    if (item.jenis === "Pengeluaran") {
      acc[kategori].jumlah += Number(item.jumlah) || 0;
    }

    return acc;
  }, {});

  const kategoriData = Object.values(kategoriDataObj)
    .filter((item) => item.jumlah > 0)
    .sort((a, b) => b.jumlah - a.jumlah);

  const skorTransparansi =
    summary.total_transaksi > 0
      ? Math.min(100, 70 + Math.min(30, summary.total_transaksi * 3))
      : 0;

  const laporanUnduh = [
    {
      title: "Rekap Transaksi Dana MBG",
      type: "CSV",
      date: "Data real-time",
      icon: FileText,
    },
  ];

  if (loading) {
    return (
      <div className="flex min-h-[60vh] items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary/20 border-t-primary" />
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-7xl px-4 py-10 sm:px-6 lg:px-8">
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
        <SectionTitle
          title="Laporan & Analisis"
          subtitle={
            isAdmin
              ? "Admin dapat mengelola transaksi dana dan melihat rekap transparansi MBG."
              : "Pemerintah dapat memantau laporan dana, rekap distribusi, dan analisis transparansi MBG."
          }
        />

        <div className="flex flex-wrap gap-2 print:hidden">
          <Button variant="outline" onClick={loadData} className="w-fit">
            <RefreshCw className="mr-2 h-4 w-4" />
            Refresh
          </Button>

          <Button variant="outline" onClick={handlePrint} className="w-fit">
            <FileText className="mr-2 h-4 w-4" />
            Cetak / PDF
          </Button>

          <Button onClick={exportRekapCSV} className="w-fit">
            <Download className="mr-2 h-4 w-4" />
            Export Rekap
          </Button>
        </div>
      </div>

      {isPemerintah && (
        <div className="mb-6 rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm text-blue-800">
          <div className="flex items-start gap-3">
            <ShieldCheck className="mt-0.5 h-5 w-5 flex-shrink-0" />
            <div>
              <p className="font-black">Mode Pemantauan Pemerintah</p>
              <p className="mt-1 leading-relaxed">
                Akun pemerintah hanya dapat melihat laporan, mencetak PDF, dan
                mengunduh CSV. Fitur tambah, edit, dan hapus transaksi hanya
                tersedia untuk admin.
              </p>
            </div>
          </div>
        </div>
      )}

      {error && (
        <div className="mb-6 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-600">
          {error}
        </div>
      )}

      <div className="mb-8 grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-4">
        <StatCard
          label="Rekap SPPG"
          value={Number(rekap.ringkasan.total_sppg || 0).toLocaleString("id-ID")}
        />

        <StatCard
          label="Rekap Dana"
          value={formatShortRp(rekap.ringkasan.total_dana)}
          color="text-emerald-600"
        />

        <StatCard
          label="Rekap Siswa"
          value={Number(rekap.ringkasan.total_siswa || 0).toLocaleString("id-ID")}
          color="text-primary"
        />

        <StatCard
          label="Belum Tersalurkan"
          value={Number(rekap.ringkasan.belum_tersalurkan || 0).toLocaleString("id-ID")}
          color="text-red-600"
        />
      </div>

      <div className="mb-8 rounded-xl border border-border bg-card p-5 print:break-inside-avoid">
        <div className="mb-5 flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <h3 className="font-bold text-foreground">Rekap Laporan Gabungan</h3>
            <p className="mt-1 text-sm text-muted-foreground">
              Ringkasan menyeluruh dari SPPG, bahan stok rendah, laporan
              operasional, dan pengaduan.
            </p>
          </div>

          <div className="flex flex-wrap gap-2 print:hidden">
            <Button variant="outline" size="sm" onClick={exportRekapCSV}>
              <Download className="mr-1 h-4 w-4" />
              Unduh Rekap CSV
            </Button>
          </div>
        </div>

        <div className="grid grid-cols-1 gap-4 md:grid-cols-4">
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Total Sekolah</p>
            <p className="text-xl font-bold">
              {Number(rekap.ringkasan.total_sekolah || 0).toLocaleString("id-ID")}
            </p>
          </div>

          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Total Karyawan</p>
            <p className="text-xl font-bold">
              {Number(rekap.ringkasan.total_karyawan || 0).toLocaleString("id-ID")}
            </p>
          </div>

          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Total Bahan</p>
            <p className="text-xl font-bold">
              {Number(rekap.ringkasan.total_bahan || 0).toLocaleString("id-ID")}
            </p>
          </div>

          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Total Pengaduan</p>
            <p className="text-xl font-bold">
              {Number(rekap.ringkasan.total_pengaduan || 0).toLocaleString("id-ID")}
            </p>
          </div>
        </div>

        <div className="mt-4 grid grid-cols-1 gap-4 md:grid-cols-3">
          <div className="rounded-lg border border-emerald-100 bg-emerald-50 p-4">
            <p className="text-sm text-emerald-700">Total Porsi</p>
            <p className="text-xl font-bold text-emerald-700">
              {Number(rekap.ringkasan.total_porsi || 0).toLocaleString("id-ID")}
            </p>
          </div>

          <div className="rounded-lg border border-blue-100 bg-blue-50 p-4">
            <p className="text-sm text-blue-700">Terdistribusi</p>
            <p className="text-xl font-bold text-blue-700">
              {Number(rekap.ringkasan.total_terdistribusi || 0).toLocaleString("id-ID")}
            </p>
          </div>

          <div className="rounded-lg border border-red-100 bg-red-50 p-4">
            <p className="text-sm text-red-700">Belum Tersalurkan</p>
            <p className="text-xl font-bold text-red-700">
              {Number(rekap.ringkasan.belum_tersalurkan || 0).toLocaleString("id-ID")}
            </p>
          </div>
        </div>
      </div>

      <div className="mb-6 rounded-xl border border-border bg-card p-4">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
          <div>
            <p className="text-sm font-medium">Filter SPPG</p>
            <p className="text-xs text-muted-foreground">
              Pilih semua SPPG atau salah satu SPPG tertentu.
            </p>
          </div>

          <select
            value={filterSppg}
            onChange={(e) => setFilterSppg(e.target.value)}
            className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm sm:w-72"
          >
            <option value="all">Semua SPPG</option>

            {sppgList.map((s) => (
              <option key={s.id} value={s.id}>
                {s.nama}
              </option>
            ))}
          </select>
        </div>
      </div>

      {isAdmin && (
        <div className="mb-8 rounded-xl border border-border bg-card p-5">
          <div className="mb-1 flex items-center gap-2">
            <Plus className="h-5 w-5 text-primary" />
            <h3 className="font-bold text-foreground">Tambah Transaksi Dana</h3>
          </div>

          <p className="mb-5 text-sm text-muted-foreground">
            Input pemasukan atau pengeluaran dana SPPG. Form ini hanya tersedia
            untuk admin.
          </p>

          <form
            onSubmit={handleSubmit}
            className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4"
          >
            <div>
              <label className="mb-1.5 block text-sm font-medium">SPPG</label>

              <select
                name="sppg_id"
                value={form.sppg_id}
                onChange={handleChange}
                className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                required
              >
                <option value="">Pilih SPPG</option>

                {sppgList.map((s) => (
                  <option key={s.id} value={s.id}>
                    {s.nama}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="mb-1.5 block text-sm font-medium">Tanggal</label>

              <input
                name="tanggal"
                type="date"
                value={form.tanggal}
                onChange={handleChange}
                className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                required
              />
            </div>

            <div>
              <label className="mb-1.5 block text-sm font-medium">Jenis</label>

              <select
                name="jenis"
                value={form.jenis}
                onChange={handleChange}
                className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              >
                <option value="Pemasukan">Pemasukan</option>
                <option value="Pengeluaran">Pengeluaran</option>
              </select>
            </div>

            <div>
              <label className="mb-1.5 block text-sm font-medium">Kategori</label>

              <select
                name="kategori"
                value={form.kategori}
                onChange={handleChange}
                className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                required
              >
                <option value="">Pilih kategori</option>
                <option value="Pemasukan">Pemasukan</option>
                <option value="Bahan Makanan">Bahan Makanan</option>
                <option value="Operasional">Operasional</option>
                <option value="Distribusi">Distribusi</option>
                <option value="Transportasi">Transportasi</option>
                <option value="Lainnya">Lainnya</option>
              </select>
            </div>

            <div>
              <label className="mb-1.5 block text-sm font-medium">Supplier</label>

              <input
                name="supplier"
                value={form.supplier}
                onChange={handleChange}
                placeholder="Contoh: CV Pangan Sehat"
                className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              />
            </div>

            <div>
              <label className="mb-1.5 block text-sm font-medium">Jumlah</label>

              <input
                name="jumlah"
                type="number"
                value={form.jumlah}
                onChange={handleChange}
                placeholder="Contoh: 12000000"
                className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                required
              />
            </div>

            <div className="md:col-span-2">
              <label className="mb-1.5 block text-sm font-medium">Deskripsi</label>

              <input
                name="deskripsi"
                value={form.deskripsi}
                onChange={handleChange}
                placeholder="Contoh: Pembelian beras, telur, sayur"
                className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              />
            </div>

            <div className="flex justify-end lg:col-span-4">
              <Button type="submit" disabled={submitting}>
                {submitting ? "Menyimpan..." : "Tambah Transaksi"}
              </Button>
            </div>
          </form>
        </div>
      )}

      <div className="mb-8 grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-4">
        <StatCard
          label="Total Pemasukan"
          value={formatShortRp(summary.total_pemasukan)}
          color="text-emerald-600"
        />

        <StatCard
          label="Total Pengeluaran"
          value={formatShortRp(summary.total_pengeluaran)}
          color="text-red-600"
        />

        <StatCard
          label="Sisa Dana"
          value={formatShortRp(summary.sisa_dana)}
          color="text-primary"
        />

        <StatCard
          label="Total Transaksi"
          value={Number(summary.total_transaksi || 0).toLocaleString("id-ID")}
          color="text-amber-600"
        />
      </div>

      <div className="mb-8 grid grid-cols-2 gap-3 sm:gap-4 lg:grid-cols-4">
        <StatCard
          label="Skor Transparansi"
          value={`${skorTransparansi}/100`}
          color="text-primary"
        />

        <StatCard
          label="Jumlah SPPG"
          value={
            filterSppg === "all"
              ? sppgList.length.toLocaleString("id-ID")
              : "1"
          }
          color="text-emerald-600"
        />

        <StatCard
          label="Status Dana"
          value={summary.sisa_dana >= 0 ? "Aman" : "Minus"}
          color={summary.sisa_dana >= 0 ? "text-green-600" : "text-red-600"}
        />

        <StatCard
          label="Update Terakhir"
          value="Real-time"
          color="text-muted-foreground"
        />
      </div>

      <div className="mb-8 grid grid-cols-1 gap-6 lg:grid-cols-2">
        <div className="rounded-xl border border-border bg-card p-5 sm:p-6">
          <h3 className="mb-2 font-bold text-foreground">Tren Dana Bulanan</h3>

          <p className="mb-4 text-sm text-muted-foreground">
            Perbandingan pemasukan dan pengeluaran berdasarkan bulan transaksi.
          </p>

          {trendData.length === 0 ? (
            <div className="py-16 text-center text-sm text-muted-foreground">
              Belum ada data transaksi.
            </div>
          ) : (
            <ResponsiveContainer width="100%" height={300}>
              <AreaChart data={trendData}>
                <defs>
                  <linearGradient
                    id="colorPemasukan"
                    x1="0"
                    y1="0"
                    x2="0"
                    y2="1"
                  >
                    <stop offset="5%" stopColor="#16a34a" stopOpacity={0.25} />
                    <stop offset="95%" stopColor="#16a34a" stopOpacity={0} />
                  </linearGradient>

                  <linearGradient
                    id="colorPengeluaran"
                    x1="0"
                    y1="0"
                    x2="0"
                    y2="1"
                  >
                    <stop offset="5%" stopColor="#dc2626" stopOpacity={0.22} />
                    <stop offset="95%" stopColor="#dc2626" stopOpacity={0} />
                  </linearGradient>
                </defs>

                <CartesianGrid
                  strokeDasharray="3 3"
                  vertical={false}
                  stroke="#e5e7eb"
                />

                <XAxis
                  dataKey="bulan"
                  fontSize={12}
                  tickLine={false}
                  axisLine={false}
                />

                <YAxis
                  fontSize={12}
                  tickLine={false}
                  axisLine={false}
                  tickFormatter={(v) => `${v / 1000000}jt`}
                />

                <Tooltip formatter={(value) => formatRp(value)} />

                <Area
                  type="monotone"
                  dataKey="pemasukan"
                  name="Pemasukan"
                  stroke="#16a34a"
                  strokeWidth={2.5}
                  fill="url(#colorPemasukan)"
                />

                <Area
                  type="monotone"
                  dataKey="pengeluaran"
                  name="Pengeluaran"
                  stroke="#dc2626"
                  strokeWidth={2.5}
                  fill="url(#colorPengeluaran)"
                />
              </AreaChart>
            </ResponsiveContainer>
          )}
        </div>

        <div className="rounded-xl border border-border bg-card p-5 sm:p-6">
          <h3 className="mb-2 font-bold text-foreground">
            Pengeluaran per Kategori
          </h3>

          <p className="mb-4 text-sm text-muted-foreground">
            Ringkasan nominal pengeluaran berdasarkan kategori transaksi.
          </p>

          {kategoriData.length === 0 ? (
            <div className="py-16 text-center text-sm text-muted-foreground">
              Belum ada data pengeluaran.
            </div>
          ) : (
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={kategoriData}>
                <CartesianGrid
                  strokeDasharray="3 3"
                  vertical={false}
                  stroke="#e5e7eb"
                />

                <XAxis
                  dataKey="kategori"
                  fontSize={12}
                  tickLine={false}
                  axisLine={false}
                />

                <YAxis
                  fontSize={12}
                  tickLine={false}
                  axisLine={false}
                  tickFormatter={(v) => `${v / 1000000}jt`}
                />

                <Tooltip formatter={(value) => formatRp(value)} />

                <Bar
                  dataKey="jumlah"
                  name="Pengeluaran"
                  fill="#f59e0b"
                  radius={[8, 8, 0, 0]}
                />
              </BarChart>
            </ResponsiveContainer>
          )}
        </div>
      </div>

      <div className="mb-8 overflow-hidden rounded-xl border border-border bg-card">
        <div className="border-b border-border p-5 sm:p-6">
          <h3 className="font-bold text-foreground">Daftar Transaksi Dana</h3>

          <p className="mt-1 text-sm text-muted-foreground">
            Data transaksi pemasukan dan pengeluaran yang tercatat di sistem.
          </p>
        </div>

        {transaksiList.length === 0 ? (
          <div className="py-16 text-center text-sm text-muted-foreground">
            Belum ada transaksi.
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-primary/5">
                <tr>
                  <th className="px-4 py-3 text-left font-semibold">Tanggal</th>
                  <th className="px-4 py-3 text-left font-semibold">SPPG</th>
                  <th className="px-4 py-3 text-left font-semibold">Kategori</th>
                  <th className="px-4 py-3 text-left font-semibold">Deskripsi</th>
                  <th className="px-4 py-3 text-left font-semibold">Supplier</th>
                  <th className="px-4 py-3 text-left font-semibold">Jenis</th>
                  <th className="px-4 py-3 text-right font-semibold">Jumlah</th>

                  {isAdmin && (
                    <th className="px-4 py-3 text-center font-semibold">
                      Aksi
                    </th>
                  )}
                </tr>
              </thead>

              <tbody className="divide-y divide-border">
                {transaksiList.map((t) => (
                  <tr key={t.id} className="hover:bg-muted/30">
                    {isAdmin && editId === t.id ? (
                      <>
                        <td className="px-4 py-3">
                          <input
                            name="tanggal"
                            type="date"
                            value={editForm.tanggal}
                            onChange={handleEditChange}
                            className="w-full rounded-md border border-input bg-background px-2 py-1 text-sm"
                          />
                        </td>

                        <td className="px-4 py-3">
                          <select
                            name="sppg_id"
                            value={editForm.sppg_id}
                            onChange={handleEditChange}
                            className="w-full rounded-md border border-input bg-background px-2 py-1 text-sm"
                          >
                            <option value="">Pilih SPPG</option>

                            {sppgList.map((s) => (
                              <option key={s.id} value={s.id}>
                                {s.nama}
                              </option>
                            ))}
                          </select>
                        </td>

                        <td className="px-4 py-3">
                          <select
                            name="kategori"
                            value={editForm.kategori}
                            onChange={handleEditChange}
                            className="w-full rounded-md border border-input bg-background px-2 py-1 text-sm"
                          >
                            <option value="">Pilih kategori</option>
                            <option value="Pemasukan">Pemasukan</option>
                            <option value="Bahan Makanan">Bahan Makanan</option>
                            <option value="Operasional">Operasional</option>
                            <option value="Distribusi">Distribusi</option>
                            <option value="Transportasi">Transportasi</option>
                            <option value="Lainnya">Lainnya</option>
                          </select>
                        </td>

                        <td className="px-4 py-3">
                          <input
                            name="deskripsi"
                            value={editForm.deskripsi}
                            onChange={handleEditChange}
                            className="w-full rounded-md border border-input bg-background px-2 py-1 text-sm"
                          />
                        </td>

                        <td className="px-4 py-3">
                          <input
                            name="supplier"
                            value={editForm.supplier}
                            onChange={handleEditChange}
                            className="w-full rounded-md border border-input bg-background px-2 py-1 text-sm"
                          />
                        </td>

                        <td className="px-4 py-3">
                          <select
                            name="jenis"
                            value={editForm.jenis}
                            onChange={handleEditChange}
                            className="w-full rounded-md border border-input bg-background px-2 py-1 text-sm"
                          >
                            <option value="Pemasukan">Pemasukan</option>
                            <option value="Pengeluaran">Pengeluaran</option>
                          </select>
                        </td>

                        <td className="px-4 py-3">
                          <input
                            name="jumlah"
                            type="number"
                            value={editForm.jumlah}
                            onChange={handleEditChange}
                            className="w-full rounded-md border border-input bg-background px-2 py-1 text-right text-sm"
                          />
                        </td>

                        <td className="px-4 py-3">
                          <div className="flex items-center justify-center gap-2">
                            <Button
                              size="sm"
                              onClick={() => handleUpdate(t.id)}
                              disabled={updating}
                            >
                              <Save className="mr-1 h-4 w-4" />
                              Simpan
                            </Button>

                            <Button size="sm" variant="outline" onClick={cancelEdit}>
                              <X className="mr-1 h-4 w-4" />
                              Batal
                            </Button>
                          </div>
                        </td>
                      </>
                    ) : (
                      <>
                        <td className="whitespace-nowrap px-4 py-3">
                          {t.tanggal || "-"}
                        </td>

                        <td className="px-4 py-3 font-medium">
                          {t.sppg_nama || "-"}
                        </td>

                        <td className="px-4 py-3">{t.kategori || "-"}</td>

                        <td className="max-w-xs px-4 py-3">
                          <p className="line-clamp-2">{t.deskripsi || "-"}</p>
                        </td>

                        <td className="px-4 py-3">{t.supplier || "-"}</td>

                        <td className="px-4 py-3">
                          <span
                            className={`rounded-full px-2 py-0.5 text-xs font-semibold ${
                              t.jenis === "Pemasukan"
                                ? "bg-emerald-100 text-emerald-700"
                                : "bg-red-100 text-red-700"
                            }`}
                          >
                            {t.jenis || "-"}
                          </span>
                        </td>

                        <td className="px-4 py-3 text-right font-semibold">
                          {formatRp(t.jumlah)}
                        </td>

                        {isAdmin && (
                          <td className="px-4 py-3 text-center">
                            <div className="flex items-center justify-center gap-2">
                              <Button
                                size="sm"
                                variant="outline"
                                onClick={() => startEdit(t)}
                              >
                                <Pencil className="mr-1 h-4 w-4" />
                                Edit
                              </Button>

                              <Button
                                size="sm"
                                variant="destructive"
                                onClick={() => handleDelete(t.id)}
                              >
                                <Trash2 className="mr-1 h-4 w-4" />
                                Hapus
                              </Button>
                            </div>
                          </td>
                        )}
                      </>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <div className="mb-8 grid grid-cols-1 gap-6 lg:grid-cols-2">
        <div className="overflow-hidden rounded-xl border border-border bg-card">
          <div className="border-b border-border p-5">
            <h3 className="font-bold text-foreground">Bahan Stok Rendah</h3>
            <p className="mt-1 text-sm text-muted-foreground">
              Bahan makanan dengan stok maksimal 10.
            </p>
          </div>

          {rekap.bahan_stok_rendah.length === 0 ? (
            <div className="py-12 text-center text-sm text-muted-foreground">
              Tidak ada bahan dengan stok rendah.
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-primary/5">
                  <tr>
                    <th className="px-4 py-3 text-left font-semibold">Bahan</th>
                    <th className="px-4 py-3 text-left font-semibold">Kategori</th>
                    <th className="px-4 py-3 text-right font-semibold">Stok</th>
                    <th className="px-4 py-3 text-right font-semibold">Harga</th>
                  </tr>
                </thead>

                <tbody className="divide-y divide-border">
                  {rekap.bahan_stok_rendah.slice(0, 8).map((item) => (
                    <tr key={item.id} className="hover:bg-muted/30">
                      <td className="px-4 py-3 font-medium">
                        {item.nama_bahan || "-"}
                      </td>
                      <td className="px-4 py-3 text-muted-foreground">
                        {item.kategori || "-"}
                      </td>
                      <td className="px-4 py-3 text-right">
                        {Number(item.stok || 0).toLocaleString("id-ID")}{" "}
                        {item.satuan || ""}
                      </td>
                      <td className="px-4 py-3 text-right">
                        {formatRp(item.harga_satuan)}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>

        <div className="overflow-hidden rounded-xl border border-border bg-card">
          <div className="border-b border-border p-5">
            <h3 className="font-bold text-foreground">
              Laporan Operasional Terbaru
            </h3>
            <p className="mt-1 text-sm text-muted-foreground">
              Ringkasan laporan dapur dan distribusi porsi.
            </p>
          </div>

          {rekap.laporan_operasional.length === 0 ? (
            <div className="py-12 text-center text-sm text-muted-foreground">
              Belum ada laporan operasional.
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-primary/5">
                  <tr>
                    <th className="px-4 py-3 text-left font-semibold">Tanggal</th>
                    <th className="px-4 py-3 text-left font-semibold">Menu</th>
                    <th className="px-4 py-3 text-right font-semibold">
                      Distribusi
                    </th>
                    <th className="px-4 py-3 text-left font-semibold">Status</th>
                  </tr>
                </thead>

                <tbody className="divide-y divide-border">
                  {rekap.laporan_operasional.slice(0, 8).map((item) => (
                    <tr key={item.id} className="hover:bg-muted/30">
                      <td className="whitespace-nowrap px-4 py-3">
                        {item.tanggal || "-"}
                      </td>
                      <td className="max-w-xs px-4 py-3">
                        <p className="line-clamp-2">{item.menu_makanan || "-"}</p>
                      </td>
                      <td className="px-4 py-3 text-right">
                        {Number(item.jumlah_terdistribusi || 0).toLocaleString(
                          "id-ID"
                        )}{" "}
                        /{" "}
                        {Number(item.jumlah_porsi || 0).toLocaleString("id-ID")}
                      </td>
                      <td className="px-4 py-3">{item.status || "-"}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      <div className="overflow-hidden rounded-xl border border-border bg-card">
        <div className="border-b border-border p-5 sm:p-6">
          <h3 className="font-bold text-foreground">Unduh Laporan</h3>

          <p className="mt-1 text-sm text-muted-foreground">
            Unduh data transaksi yang sedang tampil dalam format CSV.
          </p>
        </div>

        <div className="divide-y divide-border">
          {laporanUnduh.map((r, idx) => (
            <div
              key={idx}
              className="flex items-center gap-4 p-4 transition-colors hover:bg-muted/30 sm:p-5"
            >
              <div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-lg bg-primary/10">
                <r.icon className="h-5 w-5 text-primary" />
              </div>

              <div className="min-w-0 flex-1">
                <p className="text-sm font-semibold text-foreground">{r.title}</p>

                <div className="mt-0.5 flex items-center gap-2">
                  <Calendar className="h-3.5 w-3.5 text-muted-foreground" />
                  <span className="text-xs text-muted-foreground">
                    {r.date}
                  </span>
                  <span className="rounded bg-muted px-2 py-0.5 text-xs font-medium">
                    {r.type}
                  </span>
                </div>
              </div>

              <Button
                size="sm"
                variant="outline"
                className="rounded-full border-primary/30 text-primary hover:bg-primary/5"
                onClick={exportCSV}
              >
                <Download className="mr-1 h-3.5 w-3.5" />
                Unduh CSV
              </Button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}