import { useEffect, useRef, useState } from "react";
import { useParams, Link } from "react-router-dom";
import {
  ArrowLeft,
  MapPin,
  Users,
  Wallet,
  CheckCircle,
  Calendar,
  Building2,
  School,
  Plus,
  Pencil,
  Trash2,
  X,
  Save,
  UserRound,
  Package,
} from "lucide-react";

import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import SectionTitle from "../components/SectionTitle";  
import { createAuditLog } from "../utils/auditLogger";
import TrackingDistribusi from "../components/TrackingDistribusi";
import MenuMakananHarian from "../components/MenuMakananHarian";

const DETAIL_API = "http://localhost/backend/api/sppg/detail.php";

const SEKOLAH_API = "http://localhost/backend/api/sekolah/list.php";
const CREATE_SEKOLAH_API = "http://localhost/backend/api/sekolah/create.php";
const UPDATE_SEKOLAH_API = "http://localhost/backend/api/sekolah/update.php";
const DELETE_SEKOLAH_API = "http://localhost/backend/api/sekolah/delete.php";

const KARYAWAN_API = "http://localhost/backend/api/karyawan/list.php";
const CREATE_KARYAWAN_API = "http://localhost/backend/api/karyawan/create.php";
const UPDATE_KARYAWAN_API = "http://localhost/backend/api/karyawan/update.php";
const DELETE_KARYAWAN_API = "http://localhost/backend/api/karyawan/delete.php";

const BAHAN_API = "http://localhost/backend/api/bahan/list.php";
const CREATE_BAHAN_API = "http://localhost/backend/api/bahan/create.php";
const UPDATE_BAHAN_API = "http://localhost/backend/api/bahan/update.php";
const DELETE_BAHAN_API = "http://localhost/backend/api/bahan/delete.php";

const OMPRENGAN_API = "http://localhost/backend/api/omprengan/list.php";
const CREATE_OMPRENGAN_API = "http://localhost/backend/api/omprengan/create.php";
const UPDATE_OMPRENGAN_API = "http://localhost/backend/api/omprengan/update.php";
const DELETE_OMPRENGAN_API = "http://localhost/backend/api/omprengan/delete.php";

const LAPORAN_API = "http://localhost/backend/api/laporan/list.php";
const CREATE_LAPORAN_API = "http://localhost/backend/api/laporan/create.php";
const UPDATE_LAPORAN_API = "http://localhost/backend/api/laporan/update.php";
const DELETE_LAPORAN_API = "http://localhost/backend/api/laporan/delete.php";

const TRANSAKSI_API = "http://localhost/backend/api/transaksi/list.php";
const TRANSAKSI_SUMMARY_API = "http://localhost/backend/api/transaksi/summary.php";

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

const formatTanggalIndonesia = (value) => {
  if (!value) return "-";

  return new Date(value).toLocaleDateString("id-ID", {
    day: "2-digit",
    month: "long",
    year: "numeric",
  });
};

const statusClass = (status) => {
  if (["Aktif", "Selesai", "Baik", "Aman", "Sangat Baik"].includes(status)) {
    return "bg-emerald-100 text-emerald-700";
  }

  if (["Draft", "Rusak Ringan", "Menipis", "Cukup Baik"].includes(status)) {
    return "bg-yellow-100 text-yellow-700";
  }

  return "bg-red-100 text-red-700";
};

export default function DetailSPPG() {
  const { id } = useParams();
  const detailLoggedRef = useRef(false);

  const [sppg, setSppg] = useState(null);
  const [sekolahList, setSekolahList] = useState([]);
  const [karyawanList, setKaryawanList] = useState([]);
  const [bahanList, setBahanList] = useState([]);
  const [omprenganList, setOmprenganList] = useState([]);
  const [laporanList, setLaporanList] = useState([]);
  const [transaksiList, setTransaksiList] = useState([]);

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

  const [formSekolah, setFormSekolah] = useState({
    nama_sekolah: "",
    jenjang: "",
    jumlah_siswa: "",
  });

  const [editId, setEditId] = useState(null);
  const [editForm, setEditForm] = useState({
    nama_sekolah: "",
    jenjang: "",
    jumlah_siswa: "",
  });

  const [formKaryawan, setFormKaryawan] = useState({
    nama: "",
    jabatan: "",
    no_hp: "",
    alamat: "",
    gaji: "",
    status: "Aktif",
  });

  const [editKaryawanId, setEditKaryawanId] = useState(null);
  const [editKaryawanForm, setEditKaryawanForm] = useState({
    nama: "",
    jabatan: "",
    no_hp: "",
    alamat: "",
    gaji: "",
    status: "Aktif",
  });

  const [formBahan, setFormBahan] = useState({
    nama_bahan: "",
    kategori: "",
    satuan: "kg",
    stok: "",
    harga_satuan: "",
    tanggal_masuk: "",
  });

  const [editBahanId, setEditBahanId] = useState(null);
  const [editBahanForm, setEditBahanForm] = useState({
    nama_bahan: "",
    kategori: "",
    satuan: "kg",
    stok: "",
    harga_satuan: "",
    tanggal_masuk: "",
  });

  const [formOmprengan, setFormOmprengan] = useState({
    nama_barang: "",
    kategori: "",
    jumlah: "",
    kondisi: "Baik",
    keterangan: "",
  });

  const [editOmprenganId, setEditOmprenganId] = useState(null);
  const [editOmprenganForm, setEditOmprenganForm] = useState({
    nama_barang: "",
    kategori: "",
    jumlah: "",
    kondisi: "Baik",
    keterangan: "",
  });

  const [formLaporan, setFormLaporan] = useState({
    tanggal: "",
    menu_makanan: "",
    jumlah_porsi: "",
    jumlah_terdistribusi: "",
    kendala: "",
    catatan: "",
    status: "Draft",
  });

  const [editLaporanId, setEditLaporanId] = useState(null);
  const [editLaporanForm, setEditLaporanForm] = useState({
    tanggal: "",
    menu_makanan: "",
    jumlah_porsi: "",
    jumlah_terdistribusi: "",
    kendala: "",
    catatan: "",
    status: "Draft",
  });

  const [loading, setLoading] = useState(true);
  const [savingSekolah, setSavingSekolah] = useState(false);
  const [updatingSekolah, setUpdatingSekolah] = useState(false);
  const [savingKaryawan, setSavingKaryawan] = useState(false);
  const [updatingKaryawan, setUpdatingKaryawan] = useState(false);
  const [savingBahan, setSavingBahan] = useState(false);
  const [updatingBahan, setUpdatingBahan] = useState(false);
  const [savingOmprengan, setSavingOmprengan] = useState(false);
  const [updatingOmprengan, setUpdatingOmprengan] = useState(false);
  const [savingLaporan, setSavingLaporan] = useState(false);
  const [updatingLaporan, setUpdatingLaporan] = useState(false);
  const [error, setError] = useState("");

  const [filterBahan, setFilterBahan] = useState("semua");
  const [filterOmprengan, setFilterOmprengan] = useState("semua");
  const [filterLaporan, setFilterLaporan] = useState("semua");
  const [filterTransaksi, setFilterTransaksi] = useState("semua");
  const [searchKeyword, setSearchKeyword] = useState("");
  const [activeTab, setActiveTab] = useState("info");

  const role = localStorage.getItem("role");
  const isAdmin = role === "admin";

  useEffect(() => {
    detailLoggedRef.current = false;
    loadDetail();
  }, [id]);

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

      const res = await fetch(`${DETAIL_API}?id=${id}`);

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

      const result = await res.json();

      if (!result.success) {
        setError(result.message || "Data SPPG tidak ditemukan");
        setSppg(null);
        setSekolahList([]);
        setKaryawanList([]);
        setBahanList([]);
        setOmprenganList([]);
        setLaporanList([]);
        setTransaksiList([]);
        return;
      }

      setSppg(result.data);

      if (!detailLoggedRef.current) {
        createAuditLog({
          aksi: "Melihat Detail SPPG",
          target: "SPPG",
          keterangan: `Admin membuka detail SPPG ${result.data.nama || "-"}.`,
        });

        detailLoggedRef.current = true;
      }

      const [sekolahRes, karyawanRes, bahanRes, omprenganRes, laporanRes, transaksiRes, summaryRes] = await Promise.all([
        fetch(`${SEKOLAH_API}?sppg_id=${id}`),
        fetch(`${KARYAWAN_API}?sppg_id=${id}`),
        fetch(`${BAHAN_API}?sppg_id=${id}`),
        fetch(`${OMPRENGAN_API}?sppg_id=${id}`),
        fetch(`${LAPORAN_API}?sppg_id=${id}`),
        fetch(`${TRANSAKSI_API}?sppg_id=${id}`),
        fetch(`${TRANSAKSI_SUMMARY_API}?sppg_id=${id}`),
      ]);

      if (!sekolahRes.ok) throw new Error(`HTTP Error sekolah ${sekolahRes.status}`);
      if (!karyawanRes.ok) throw new Error(`HTTP Error karyawan ${karyawanRes.status}`);
      if (!bahanRes.ok) throw new Error(`HTTP Error bahan ${bahanRes.status}`);
      if (!omprenganRes.ok) throw new Error(`HTTP Error omprengan ${omprenganRes.status}`);
      if (!laporanRes.ok) throw new Error(`HTTP Error laporan ${laporanRes.status}`);
      if (!transaksiRes.ok) throw new Error(`HTTP Error transaksi ${transaksiRes.status}`);
      if (!summaryRes.ok) throw new Error(`HTTP Error summary transaksi ${summaryRes.status}`);

      const sekolahResult = await sekolahRes.json();
      const karyawanResult = await karyawanRes.json();
      const bahanResult = await bahanRes.json();
      const omprenganResult = await omprenganRes.json();
      const laporanResult = await laporanRes.json();
      const transaksiResult = await transaksiRes.json();
      const summaryResult = await summaryRes.json();

      setSekolahList(sekolahResult.success && Array.isArray(sekolahResult.data) ? sekolahResult.data : []);
      setKaryawanList(karyawanResult.success && Array.isArray(karyawanResult.data) ? karyawanResult.data : []);
      setBahanList(bahanResult.success && Array.isArray(bahanResult.data) ? bahanResult.data : []);
      setOmprenganList(omprenganResult.success && Array.isArray(omprenganResult.data) ? omprenganResult.data : []);
      setLaporanList(laporanResult.success && Array.isArray(laporanResult.data) ? laporanResult.data : []);
      setTransaksiList(transaksiResult.success && Array.isArray(transaksiResult.data) ? transaksiResult.data : []);
      setSummaryTransaksi(
        summaryResult.success && summaryResult.data
          ? summaryResult.data
          : {
              total_pemasukan: 0,
              total_pengeluaran: 0,
              sisa_dana: 0,
              total_transaksi: 0,
            }
      );
    } catch (err) {
      console.error("Gagal mengambil detail SPPG:", err);
      setError("Gagal mengambil detail SPPG dari server");
      setSppg(null);
      setSekolahList([]);
      setKaryawanList([]);
      setBahanList([]);
      setOmprenganList([]);
      setLaporanList([]);
      setTransaksiList([]);
    } finally {
      setLoading(false);
    }
  };

  const handleInput = (setter) => (e) => {
    const { name, value } = e.target;
    setter((prev) => ({ ...prev, [name]: value }));
  };

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

    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    try {
      setSavingSekolah(true);
      const res = await fetch(CREATE_SEKOLAH_API, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          sppg_id: Number(id),
          nama_sekolah: formSekolah.nama_sekolah,
          jenjang: formSekolah.jenjang,
          jumlah_siswa: Number(formSekolah.jumlah_siswa) || 0,
        }),
      });

      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal menambahkan sekolah");
        return;
      }

      setFormSekolah({ nama_sekolah: "", jenjang: "", jumlah_siswa: "" });

      createAuditLog({
        aksi: "Menambah Data Sekolah",
        target: "Sekolah",
        keterangan: `Admin menambahkan sekolah ${formSekolah.nama_sekolah || "-"} pada SPPG ID ${id}.`,
      });

      await loadDetail();
    } catch (err) {
      console.error("Gagal menambahkan sekolah:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setSavingSekolah(false);
    }
  };

  const startEditSekolah = (item) => {
    setEditId(item.id);
    setEditForm({
      nama_sekolah: item.nama_sekolah || "",
      jenjang: item.jenjang || "",
      jumlah_siswa: item.jumlah_siswa || "",
    });
  };

  const cancelEditSekolah = () => {
    setEditId(null);
    setEditForm({ nama_sekolah: "", jenjang: "", jumlah_siswa: "" });
  };

  const handleUpdateSekolah = async (sekolahId) => {
    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    try {
      setUpdatingSekolah(true);
      const res = await fetch(`${UPDATE_SEKOLAH_API}?id=${sekolahId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          nama_sekolah: editForm.nama_sekolah,
          jenjang: editForm.jenjang,
          jumlah_siswa: Number(editForm.jumlah_siswa) || 0,
        }),
      });

      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal memperbarui sekolah");
        return;
      }

      cancelEditSekolah();

      createAuditLog({
        aksi: "Memperbarui Data Sekolah",
        target: "Sekolah",
        keterangan: `Admin memperbarui data sekolah ID ${sekolahId}.`,
      });

      await loadDetail();
    } catch (err) {
      console.error("Gagal update sekolah:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setUpdatingSekolah(false);
    }
  };

  const handleDeleteSekolah = async (sekolahId) => {
    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    if (!window.confirm("Yakin ingin menghapus sekolah ini?")) return;

    try {
      const res = await fetch(`${DELETE_SEKOLAH_API}?id=${sekolahId}`, {
        method: "DELETE",
      });
      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal menghapus sekolah");
        return;
      }
      createAuditLog({
        aksi: "Menghapus Data Sekolah",
        target: "Sekolah",
        keterangan: `Admin menghapus data sekolah ID ${sekolahId}.`,
      });

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

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

    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    try {
      setSavingKaryawan(true);
      const res = await fetch(CREATE_KARYAWAN_API, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          sppg_id: Number(id),
          nama: formKaryawan.nama,
          jabatan: formKaryawan.jabatan,
          no_hp: formKaryawan.no_hp,
          alamat: formKaryawan.alamat,
          gaji: Number(formKaryawan.gaji) || 0,
          status: formKaryawan.status,
        }),
      });

      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal menambahkan karyawan");
        return;
      }

      setFormKaryawan({ nama: "", jabatan: "", no_hp: "", alamat: "", gaji: "", status: "Aktif" });

      createAuditLog({
        aksi: "Menambah Data Karyawan",
        target: "Karyawan",
        keterangan: `Admin menambahkan karyawan ${formKaryawan.nama || "-"} pada SPPG ID ${id}.`,
      });

      await loadDetail();
    } catch (err) {
      console.error("Gagal menambahkan karyawan:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setSavingKaryawan(false);
    }
  };

  const startEditKaryawan = (item) => {
    setEditKaryawanId(item.id);
    setEditKaryawanForm({
      nama: item.nama || "",
      jabatan: item.jabatan || "",
      no_hp: item.no_hp || "",
      alamat: item.alamat || "",
      gaji: item.gaji || "",
      status: item.status || "Aktif",
    });
  };

  const cancelEditKaryawan = () => {
    setEditKaryawanId(null);
    setEditKaryawanForm({ nama: "", jabatan: "", no_hp: "", alamat: "", gaji: "", status: "Aktif" });
  };

  const handleUpdateKaryawan = async (karyawanId) => {
    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    try {
      setUpdatingKaryawan(true);
      const res = await fetch(`${UPDATE_KARYAWAN_API}?id=${karyawanId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          nama: editKaryawanForm.nama,
          jabatan: editKaryawanForm.jabatan,
          no_hp: editKaryawanForm.no_hp,
          alamat: editKaryawanForm.alamat,
          gaji: Number(editKaryawanForm.gaji) || 0,
          status: editKaryawanForm.status,
        }),
      });

      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal memperbarui karyawan");
        return;
      }

      cancelEditKaryawan();

      createAuditLog({
        aksi: "Memperbarui Data Karyawan",
        target: "Karyawan",
        keterangan: `Admin memperbarui data karyawan ID ${karyawanId}.`,
      });

      await loadDetail();
    } catch (err) {
      console.error("Gagal update karyawan:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setUpdatingKaryawan(false);
    }
  };

  const handleDeleteKaryawan = async (karyawanId) => {
    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    if (!window.confirm("Yakin ingin menghapus karyawan ini?")) return;

    try {
      const res = await fetch(`${DELETE_KARYAWAN_API}?id=${karyawanId}`, {
        method: "DELETE",
      });
      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal menghapus karyawan");
        return;
      }
      createAuditLog({
        aksi: "Menghapus Data Karyawan",
        target: "Karyawan",
        keterangan: `Admin menghapus data karyawan ID ${karyawanId}.`,
      });

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

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

    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    try {
      setSavingBahan(true);
      const res = await fetch(CREATE_BAHAN_API, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          sppg_id: Number(id),
          nama_bahan: formBahan.nama_bahan,
          kategori: formBahan.kategori,
          satuan: formBahan.satuan,
          stok: Number(formBahan.stok) || 0,
          harga_satuan: Number(formBahan.harga_satuan) || 0,
          tanggal_masuk: formBahan.tanggal_masuk,
        }),
      });

      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal menambahkan bahan makanan");
        return;
      }

      setFormBahan({ nama_bahan: "", kategori: "", satuan: "kg", stok: "", harga_satuan: "", tanggal_masuk: "" });

      createAuditLog({
        aksi: "Menambah Data Bahan",
        target: "Bahan Makanan",
        keterangan: `Admin menambahkan bahan makanan ${formBahan.nama_bahan || "-"} pada SPPG ID ${id}.`,
      });

      await loadDetail();
    } catch (err) {
      console.error("Gagal menambahkan bahan makanan:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setSavingBahan(false);
    }
  };

  const startEditBahan = (item) => {
    setEditBahanId(item.id);
    setEditBahanForm({
      nama_bahan: item.nama_bahan || "",
      kategori: item.kategori || "",
      satuan: item.satuan || "kg",
      stok: item.stok || "",
      harga_satuan: item.harga_satuan || "",
      tanggal_masuk: item.tanggal_masuk || "",
    });
  };

  const cancelEditBahan = () => {
    setEditBahanId(null);
    setEditBahanForm({ nama_bahan: "", kategori: "", satuan: "kg", stok: "", harga_satuan: "", tanggal_masuk: "" });
  };

  const handleUpdateBahan = async (bahanId) => {
    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    try {
      setUpdatingBahan(true);
      const res = await fetch(`${UPDATE_BAHAN_API}?id=${bahanId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          nama_bahan: editBahanForm.nama_bahan,
          kategori: editBahanForm.kategori,
          satuan: editBahanForm.satuan,
          stok: Number(editBahanForm.stok) || 0,
          harga_satuan: Number(editBahanForm.harga_satuan) || 0,
          tanggal_masuk: editBahanForm.tanggal_masuk,
        }),
      });

      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal memperbarui bahan makanan");
        return;
      }

      cancelEditBahan();

      createAuditLog({
        aksi: "Memperbarui Data Bahan",
        target: "Bahan Makanan",
        keterangan: `Admin memperbarui data bahan makanan ID ${bahanId}.`,
      });

      await loadDetail();
    } catch (err) {
      console.error("Gagal update bahan makanan:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setUpdatingBahan(false);
    }
  };

  const handleDeleteBahan = async (bahanId) => {
    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    if (!window.confirm("Yakin ingin menghapus bahan makanan ini?")) return;

    try {
      const res = await fetch(`${DELETE_BAHAN_API}?id=${bahanId}`, {
        method: "DELETE",
      });
      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal menghapus bahan makanan");
        return;
      }
      createAuditLog({
        aksi: "Menghapus Data Bahan",
        target: "Bahan Makanan",
        keterangan: `Admin menghapus data bahan makanan ID ${bahanId}.`,
      });

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

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

    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    try {
      setSavingOmprengan(true);
      const res = await fetch(CREATE_OMPRENGAN_API, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          sppg_id: Number(id),
          nama_barang: formOmprengan.nama_barang,
          kategori: formOmprengan.kategori,
          jumlah: Number(formOmprengan.jumlah) || 0,
          kondisi: formOmprengan.kondisi,
          keterangan: formOmprengan.keterangan,
        }),
      });

      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal menambahkan omprengan");
        return;
      }

      setFormOmprengan({ nama_barang: "", kategori: "", jumlah: "", kondisi: "Baik", keterangan: "" });

      createAuditLog({
        aksi: "Menambah Data Omprengan",
        target: "Omprengan",
        keterangan: `Admin menambahkan omprengan ${formOmprengan.nama_barang || "-"} pada SPPG ID ${id}.`,
      });

      await loadDetail();
    } catch (err) {
      console.error("Gagal menambahkan omprengan:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setSavingOmprengan(false);
    }
  };

  const startEditOmprengan = (item) => {
    setEditOmprenganId(item.id);
    setEditOmprenganForm({
      nama_barang: item.nama_barang || "",
      kategori: item.kategori || "",
      jumlah: item.jumlah || "",
      kondisi: item.kondisi || "Baik",
      keterangan: item.keterangan || "",
    });
  };

  const cancelEditOmprengan = () => {
    setEditOmprenganId(null);
    setEditOmprenganForm({ nama_barang: "", kategori: "", jumlah: "", kondisi: "Baik", keterangan: "" });
  };

  const handleUpdateOmprengan = async (omprenganId) => {
    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    try {
      setUpdatingOmprengan(true);
      const res = await fetch(`${UPDATE_OMPRENGAN_API}?id=${omprenganId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          nama_barang: editOmprenganForm.nama_barang,
          kategori: editOmprenganForm.kategori,
          jumlah: Number(editOmprenganForm.jumlah) || 0,
          kondisi: editOmprenganForm.kondisi,
          keterangan: editOmprenganForm.keterangan,
        }),
      });

      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal memperbarui omprengan");
        return;
      }

      cancelEditOmprengan();

      createAuditLog({
        aksi: "Memperbarui Data Omprengan",
        target: "Omprengan",
        keterangan: `Admin memperbarui data omprengan ID ${omprenganId}.`,
      });

      await loadDetail();
    } catch (err) {
      console.error("Gagal update omprengan:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setUpdatingOmprengan(false);
    }
  };

  const handleDeleteOmprengan = async (omprenganId) => {
    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    if (!window.confirm("Yakin ingin menghapus omprengan ini?")) return;

    try {
      const res = await fetch(`${DELETE_OMPRENGAN_API}?id=${omprenganId}`, {
        method: "DELETE",
      });
      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal menghapus omprengan");
        return;
      }
      createAuditLog({
        aksi: "Menghapus Data Omprengan",
        target: "Omprengan",
        keterangan: `Admin menghapus data omprengan ID ${omprenganId}.`,
      });

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

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

    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    try {
      setSavingLaporan(true);
      const res = await fetch(CREATE_LAPORAN_API, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          sppg_id: Number(id),
          tanggal: formLaporan.tanggal,
          menu_makanan: formLaporan.menu_makanan,
          jumlah_porsi: Number(formLaporan.jumlah_porsi) || 0,
          jumlah_terdistribusi: Number(formLaporan.jumlah_terdistribusi) || 0,
          kendala: formLaporan.kendala,
          catatan: formLaporan.catatan,
          status: formLaporan.status,
        }),
      });

      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal menambahkan laporan operasional");
        return;
      }

      setFormLaporan({ tanggal: "", menu_makanan: "", jumlah_porsi: "", jumlah_terdistribusi: "", kendala: "", catatan: "", status: "Draft" });

      createAuditLog({
        aksi: "Menambah Laporan Operasional",
        target: "Laporan Operasional",
        keterangan: `Admin menambahkan laporan operasional tanggal ${formLaporan.tanggal || "-"} pada SPPG ID ${id}.`,
      });

      await loadDetail();
    } catch (err) {
      console.error("Gagal menambahkan laporan operasional:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setSavingLaporan(false);
    }
  };

  const startEditLaporan = (item) => {
    setEditLaporanId(item.id);
    setEditLaporanForm({
      tanggal: item.tanggal || "",
      menu_makanan: item.menu_makanan || "",
      jumlah_porsi: item.jumlah_porsi || "",
      jumlah_terdistribusi: item.jumlah_terdistribusi || "",
      kendala: item.kendala || "",
      catatan: item.catatan || "",
      status: item.status || "Draft",
    });
  };

  const cancelEditLaporan = () => {
    setEditLaporanId(null);
    setEditLaporanForm({ tanggal: "", menu_makanan: "", jumlah_porsi: "", jumlah_terdistribusi: "", kendala: "", catatan: "", status: "Draft" });
  };

  const handleUpdateLaporan = async (laporanId) => {
    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    try {
      setUpdatingLaporan(true);
      const res = await fetch(`${UPDATE_LAPORAN_API}?id=${laporanId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          tanggal: editLaporanForm.tanggal,
          menu_makanan: editLaporanForm.menu_makanan,
          jumlah_porsi: Number(editLaporanForm.jumlah_porsi) || 0,
          jumlah_terdistribusi: Number(editLaporanForm.jumlah_terdistribusi) || 0,
          kendala: editLaporanForm.kendala,
          catatan: editLaporanForm.catatan,
          status: editLaporanForm.status,
        }),
      });

      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal memperbarui laporan operasional");
        return;
      }

      cancelEditLaporan();

      createAuditLog({
        aksi: "Memperbarui Laporan Operasional",
        target: "Laporan Operasional",
        keterangan: `Admin memperbarui laporan operasional ID ${laporanId}.`,
      });

      await loadDetail();
    } catch (err) {
      console.error("Gagal update laporan operasional:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setUpdatingLaporan(false);
    }
  };

  const handleDeleteLaporan = async (laporanId) => {
    if (!isAdmin) {
      alert("Akses ditolak. Masyarakat hanya bisa memantau data.");
      return;
    }

    if (!window.confirm("Yakin ingin menghapus laporan operasional ini?")) return;

    try {
      const res = await fetch(`${DELETE_LAPORAN_API}?id=${laporanId}`, {
        method: "DELETE",
      });
      const result = await res.json();
      if (!result.success) {
        alert(result.message || "Gagal menghapus laporan operasional");
        return;
      }
      createAuditLog({
        aksi: "Menghapus Laporan Operasional",
        target: "Laporan Operasional",
        keterangan: `Admin menghapus laporan operasional ID ${laporanId}.`,
      });

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

  const totalSiswaSekolah = sekolahList.reduce((total, item) => total + (Number(item.jumlah_siswa) || 0), 0);
  const totalGajiKaryawan = karyawanList.reduce((total, item) => total + (Number(item.gaji) || 0), 0);
  const totalNilaiBahan = bahanList.reduce((total, item) => {
    const nilai = Number(item.total_nilai) || (Number(item.stok) || 0) * (Number(item.harga_satuan) || 0);
    return total + nilai;
  }, 0);
  const totalOmprengan = omprenganList.reduce((total, item) => total + (Number(item.jumlah) || 0), 0);
  const totalPorsiLaporan = laporanList.reduce((total, item) => total + (Number(item.jumlah_porsi) || 0), 0);
  const totalTerdistribusiLaporan = laporanList.reduce((total, item) => total + (Number(item.jumlah_terdistribusi) || 0), 0);

  const persentaseDistribusi = totalPorsiLaporan > 0 ? (totalTerdistribusiLaporan / totalPorsiLaporan) * 100 : 0;
  const kekuranganDistribusi = Math.max(totalPorsiLaporan - totalTerdistribusiLaporan, 0);
  const persentasePenggunaanDana = Number(summaryTransaksi.total_pemasukan) > 0
    ? (Number(summaryTransaksi.total_pengeluaran) / Number(summaryTransaksi.total_pemasukan)) * 100
    : 0;
  const rataRataBiayaPerPorsi = totalTerdistribusiLaporan > 0
    ? Number(summaryTransaksi.total_pengeluaran) / totalTerdistribusiLaporan
    : 0;
  const totalAsetOperasional = totalNilaiBahan + totalGajiKaryawan;

  const statusDistribusi =
    totalPorsiLaporan === 0
      ? "Belum Ada Data"
      : persentaseDistribusi >= 95
      ? "Sangat Baik"
      : persentaseDistribusi >= 80
      ? "Cukup Baik"
      : "Perlu Evaluasi";

  const catatanEvaluasi =
    totalPorsiLaporan === 0
      ? "Data laporan operasional belum tersedia."
      : persentaseDistribusi >= 95
      ? "Distribusi berjalan sangat baik dan mendekati target penuh."
      : persentaseDistribusi >= 80
      ? "Distribusi cukup baik, tetapi masih perlu pemantauan pada porsi yang belum tersalurkan."
      : "Distribusi perlu dievaluasi karena selisih porsi masih cukup besar.";

  const statusDana =
    Number(summaryTransaksi.sisa_dana) < 0
      ? "Defisit"
      : persentasePenggunaanDana >= 90
      ? "Menipis"
      : "Aman";

  const totalBahanStokRendah = bahanList.filter((item) => Number(item.stok) > 0 && Number(item.stok) <= 10).length;
  const totalBarangBermasalah = omprenganList.reduce((total, item) => {
    if (["Rusak Ringan", "Rusak Berat", "Hilang"].includes(item.kondisi)) {
      return total + (Number(item.jumlah) || 0);
    }
    return total;
  }, 0);

  const tingkatPemenuhanDistribusi = totalPorsiLaporan > 0
    ? `${totalTerdistribusiLaporan.toLocaleString("id-ID")} porsi tersalurkan`
    : "Belum ada laporan porsi";

  const tindakLanjutOtomatis = [
    Number(summaryTransaksi.sisa_dana) < 0 ? "Segera evaluasi transaksi karena dana berada pada kondisi defisit." : null,
    persentasePenggunaanDana >= 90 && Number(summaryTransaksi.sisa_dana) >= 0 ? "Pantau penggunaan dana karena anggaran sudah mendekati batas pemakaian." : null,
    totalBahanStokRendah > 0 ? `Periksa ${totalBahanStokRendah} item bahan makanan yang stoknya mulai rendah.` : null,
    totalBarangBermasalah > 0 ? `Tindak lanjuti ${totalBarangBermasalah} unit omprengan/peralatan yang bermasalah.` : null,
    totalPorsiLaporan > 0 && persentaseDistribusi < 95 ? `Evaluasi distribusi karena masih ada ${kekuranganDistribusi.toLocaleString("id-ID")} porsi yang belum tersalurkan.` : null,
    laporanList.length === 0 ? "Tambahkan laporan operasional harian agar pemantauan distribusi lebih akurat." : null,
  ].filter(Boolean);

  const indikatorKelengkapan = [
    { label: "Data sekolah/penerima", lengkap: sekolahList.length > 0 },
    { label: "Data transaksi dana", lengkap: transaksiList.length > 0 || Number(summaryTransaksi.total_transaksi) > 0 },
    { label: "Data karyawan", lengkap: karyawanList.length > 0 },
    { label: "Data bahan makanan", lengkap: bahanList.length > 0 },
    { label: "Data omprengan/peralatan", lengkap: omprenganList.length > 0 },
    { label: "Laporan operasional", lengkap: laporanList.length > 0 },
  ];

  const jumlahDataLengkap = indikatorKelengkapan.filter((item) => item.lengkap).length;
  const skorKelengkapan = Math.round((jumlahDataLengkap / indikatorKelengkapan.length) * 100);
  const statusKelengkapan =
    skorKelengkapan >= 90
      ? "Sangat Lengkap"
      : skorKelengkapan >= 70
      ? "Cukup Lengkap"
      : skorKelengkapan >= 50
      ? "Perlu Dilengkapi"
      : "Belum Lengkap";
  const dataBelumLengkap = indikatorKelengkapan.filter((item) => !item.lengkap).map((item) => item.label);

  const keyword = searchKeyword.trim().toLowerCase();
  const cocokKeyword = (...values) => {
    if (!keyword) return true;
    return values.some((value) => String(value || "").toLowerCase().includes(keyword));
  };

  const sekolahTampil = sekolahList.filter((item) => cocokKeyword(item.nama_sekolah, item.jenjang, item.jumlah_siswa));
  const karyawanTampil = karyawanList.filter((item) => cocokKeyword(item.nama, item.jabatan, item.no_hp, item.alamat, item.gaji, item.status));
  const bahanTampil = bahanList.filter((item) => {
    const cocokFilter =
      filterBahan === "stok_rendah"
        ? Number(item.stok) > 0 && Number(item.stok) <= 10
        : filterBahan === "stok_habis"
        ? Number(item.stok) <= 0
        : true;
    return cocokFilter && cocokKeyword(item.nama_bahan, item.kategori, item.satuan, item.stok, item.harga_satuan, item.tanggal_masuk);
  });
  const omprenganTampil = omprenganList.filter((item) => {
    const cocokFilter =
      filterOmprengan === "bermasalah"
        ? ["Rusak Ringan", "Rusak Berat", "Hilang"].includes(item.kondisi)
        : filterOmprengan === "baik"
        ? item.kondisi === "Baik"
        : true;
    return cocokFilter && cocokKeyword(item.nama_barang, item.kategori, item.jumlah, item.kondisi, item.keterangan);
  });
  const laporanTampil = laporanList.filter((item) => {
    const cocokFilter =
      filterLaporan === "draft"
        ? item.status === "Draft"
        : filterLaporan === "selesai"
        ? item.status === "Selesai"
        : filterLaporan === "ada_kendala"
        ? Boolean(item.kendala && item.kendala.trim())
        : true;
    return cocokFilter && cocokKeyword(item.tanggal, item.menu_makanan, item.jumlah_porsi, item.jumlah_terdistribusi, item.kendala, item.catatan, item.status);
  });
  const transaksiTampil = transaksiList.filter((item) => {
    const cocokFilter =
      filterTransaksi === "pemasukan"
        ? item.jenis === "Pemasukan"
        : filterTransaksi === "pengeluaran"
        ? item.jenis === "Pengeluaran"
        : true;
    return cocokFilter && cocokKeyword(item.tanggal, item.kategori, item.deskripsi, item.supplier, item.jenis, item.jumlah);
  });

  const totalDataTampil = sekolahTampil.length + transaksiTampil.length + karyawanTampil.length + bahanTampil.length + omprenganTampil.length + laporanTampil.length;
  const dataTerbaru = {
    transaksi: transaksiList[0] || null,
    bahan: bahanList[0] || null,
    omprengan: omprenganList[0] || null,
    laporan: laporanList[0] || null,
  };

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

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

  if (error || !sppg) {
    return (
      <div className="max-w-4xl mx-auto px-4 py-16">
        <Link to="/daftar-sppg">
          <Button variant="ghost" className="mb-6">
            <ArrowLeft className="w-4 h-4 mr-2" />
            Kembali
          </Button>
        </Link>

        <div className="rounded-xl border border-red-200 bg-red-50 p-6 text-red-600">
          {error || "Data SPPG tidak ditemukan"}
        </div>
      </div>
    );
  }

  const SectionHeader = ({ title, subtitle, badges }) => (
    <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 mb-5">
      <div>
        <h3 className="text-lg font-bold">{title}</h3>
        {subtitle && <p className="text-sm text-muted-foreground mt-1">{subtitle}</p>}
      </div>
      {badges && <div className="flex flex-wrap gap-2">{badges}</div>}
    </div>
  );

  const detailTabs = [
    { key: "info", label: "Info SPPG" },
    { key: "sekolah", label: "Sekolah" },
    { key: "karyawan", label: "Karyawan" },
    { key: "bahan", label: "Bahan Makanan" },
    { key: "omprengan", label: "Omprengan" },
    { key: "rekap", label: "Rekap Dana" },
    { key: "laporan", label: "Laporan" },
    { key: "operasional", label: "Operasional Dapur" },
  ];

  return (
    <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-10 print:max-w-none print:px-0 print:py-0">
      <div className="hidden print:block mb-8 border-b pb-4">
        <h1 className="text-2xl font-bold text-center">Laporan Detail SPPG</h1>
        <p className="text-center mt-2 font-medium">{sppg.nama || "-"}</p>
        <p className="text-center text-sm">
          {sppg.kabupaten || "-"}, {sppg.provinsi || "-"}
        </p>
        <p className="text-center text-sm mt-1">
          Tanggal Cetak: {formatTanggalIndonesia(new Date())}
        </p>
      </div>

      <Link
        to="/daftar-sppg"
        className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-primary mb-6 print:hidden"
      >
        <ArrowLeft className="w-4 h-4" />
        Kembali ke Daftar SPPG
      </Link>

      <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4 mb-8">
        <SectionTitle
          title={sppg.nama || "Detail SPPG"}
          subtitle={`${sppg.kabupaten || "-"}, ${sppg.provinsi || "-"}`}
        />

        <div className="flex flex-wrap gap-2">
          <Button className="print:hidden" variant="outline" onClick={handlePrint}>
            Cetak / PDF
          </Button>
          <Badge className="w-fit">{sppg.status || "-"}</Badge>
        </div>
      </div>

      <div className="mb-8 print:hidden">
        <TrackingDistribusi sppg={sppg} />
      </div>

      <MenuMakananHarian sppgId={id} />

      <div className="rounded-2xl bg-gradient-to-r from-blue-50 via-emerald-50 to-amber-50 p-2 mb-6 print:hidden border border-blue-100 shadow-sm">
        <div className="flex gap-2 overflow-x-auto">
          {detailTabs.map((tab) => (
            <button
              key={tab.key}
              type="button"
              onClick={() => setActiveTab(tab.key)}
              className={`whitespace-nowrap rounded-xl px-4 py-2.5 text-sm font-semibold transition-all duration-200 ${
                activeTab === tab.key
                  ? "bg-blue-600 text-white shadow-md shadow-blue-200"
                  : "bg-white/75 text-slate-600 hover:bg-white hover:text-blue-700 hover:shadow-sm"
              }`}
            >
              {tab.label}
            </button>
          ))}
        </div>
      </div>

      <div className={`${activeTab === "info" ? "grid" : "hidden"} grid-cols-1 md:grid-cols-5 gap-5 mb-8 print:break-inside-avoid`}>
        {[
          { label: "Total Dana", value: formatRp(sppg.total_dana), icon: Wallet },
          { label: "Jumlah Siswa", value: (Number(sppg.jumlah_siswa) || 0).toLocaleString("id-ID"), icon: Users },
          { label: "Total Sekolah", value: sekolahList.length, icon: School },
          { label: "Total Karyawan", value: karyawanList.length, icon: UserRound },
          { label: "Total Bahan", value: bahanList.length, icon: Package },
        ].map((item) => {
          const Icon = item.icon;
          return (
            <div key={item.label} className="rounded-xl border border-border bg-card p-5">
              <div className="flex items-center gap-3 mb-3">
                <div className="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center">
                  <Icon className="w-5 h-5 text-primary" />
                </div>
                <p className="text-sm text-muted-foreground">{item.label}</p>
              </div>
              <p className="text-2xl font-bold">{item.value}</p>
            </div>
          );
        })}
      </div>

      <div className={`${activeTab === "info" ? "" : "hidden"} rounded-xl border border-border bg-card p-6 mb-8 print:break-inside-avoid`}>
        <h3 className="text-lg font-bold mb-5">Informasi SPPG</h3>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
          <div className="flex gap-3">
            <Building2 className="w-5 h-5 text-primary mt-0.5" />
            <div>
              <p className="text-sm text-muted-foreground">Nama SPPG</p>
              <p className="font-medium">{sppg.nama || "-"}</p>
            </div>
          </div>
          <div className="flex gap-3">
            <MapPin className="w-5 h-5 text-primary mt-0.5" />
            <div>
              <p className="text-sm text-muted-foreground">Wilayah</p>
              <p className="font-medium">{sppg.kabupaten || "-"}, {sppg.provinsi || "-"}</p>
            </div>
          </div>
          <div className="flex gap-3 md:col-span-2">
            <MapPin className="w-5 h-5 text-primary mt-0.5" />
            <div>
              <p className="text-sm text-muted-foreground">Alamat</p>
              <p className="font-medium">{sppg.alamat || "-"}</p>
            </div>
          </div>
          <div className="flex gap-3">
            <Calendar className="w-5 h-5 text-primary mt-0.5" />
            <div>
              <p className="text-sm text-muted-foreground">Dibuat Pada</p>
              <p className="font-medium">{sppg.created_at || "-"}</p>
            </div>
          </div>
          <div className="flex gap-3">
            <CheckCircle className="w-5 h-5 text-primary mt-0.5" />
            <div>
              <p className="text-sm text-muted-foreground">Status</p>
              <p className="font-medium">{sppg.status || "-"}</p>
            </div>
          </div>
        </div>
      </div>

      <div className={`${activeTab === "operasional" ? "" : "hidden"} rounded-xl border border-border bg-card p-6 mb-8 print:break-inside-avoid`}>
        <h3 className="text-lg font-bold mb-5">Rekap Operasional</h3>

        <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Total Gaji Karyawan</p>
            <p className="text-xl font-bold">{formatRp(totalGajiKaryawan)}</p>
          </div>
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Nilai Stok Bahan</p>
            <p className="text-xl font-bold">{formatRp(totalNilaiBahan)}</p>
          </div>
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Total Omprengan</p>
            <p className="text-xl font-bold">{totalOmprengan.toLocaleString("id-ID")} Unit</p>
          </div>
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Distribusi Porsi</p>
            <p className="text-xl font-bold">{persentaseDistribusi.toFixed(1)}%</p>
            <p className="text-xs text-muted-foreground mt-1">
              {totalTerdistribusiLaporan.toLocaleString("id-ID")} dari {totalPorsiLaporan.toLocaleString("id-ID")} porsi
            </p>
          </div>
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Status Operasional</p>
            <p className="text-xl font-bold">{statusDistribusi}</p>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mt-4">
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Kekurangan Distribusi</p>
            <p className="text-xl font-bold">{kekuranganDistribusi.toLocaleString("id-ID")} Porsi</p>
          </div>
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Penggunaan Dana</p>
            <p className="text-xl font-bold">{persentasePenggunaanDana.toFixed(1)}%</p>
          </div>
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Rata-rata Biaya/Porsi</p>
            <p className="text-xl font-bold">{formatRp(rataRataBiayaPerPorsi)}</p>
          </div>
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Aset Operasional Tercatat</p>
            <p className="text-xl font-bold">{formatRp(totalAsetOperasional)}</p>
          </div>
        </div>

        <div className="rounded-lg bg-primary/5 border border-primary/10 p-4 mt-4">
          <p className="text-sm text-muted-foreground">Catatan Evaluasi Otomatis</p>
          <p className="font-medium mt-1">{catatanEvaluasi}</p>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mt-4">
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Status Dana</p>
            <p className="text-xl font-bold">{statusDana}</p>
            <p className="text-xs text-muted-foreground mt-1">Sisa dana {formatRp(summaryTransaksi.sisa_dana)}.</p>
          </div>
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Bahan Stok Rendah</p>
            <p className="text-xl font-bold">{totalBahanStokRendah.toLocaleString("id-ID")} Item</p>
          </div>
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Barang Bermasalah</p>
            <p className="text-xl font-bold">{totalBarangBermasalah.toLocaleString("id-ID")} Unit</p>
          </div>
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Pemenuhan Distribusi</p>
            <p className="text-xl font-bold">{persentaseDistribusi.toFixed(1)}%</p>
            <p className="text-xs text-muted-foreground mt-1">{tingkatPemenuhanDistribusi}</p>
          </div>
        </div>

        <div className="rounded-lg bg-muted/30 p-4 mt-4">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 mb-3">
            <div>
              <p className="text-sm text-muted-foreground">Prioritas Tindak Lanjut</p>
              <p className="font-semibold">Rekomendasi otomatis berdasarkan data operasional</p>
            </div>
            <Badge variant="outline">{tindakLanjutOtomatis.length || 1} Catatan</Badge>
          </div>
          {tindakLanjutOtomatis.length === 0 ? (
            <p className="text-sm text-muted-foreground">Tidak ada prioritas khusus. Kondisi operasional terpantau stabil berdasarkan data yang tersedia.</p>
          ) : (
            <ol className="list-decimal pl-5 space-y-1 text-sm">
              {tindakLanjutOtomatis.map((item, index) => (
                <li key={index}>{item}</li>
              ))}
            </ol>
          )}
        </div>

        <div className="rounded-lg bg-muted/30 p-4 mt-4">
          <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3 mb-4">
            <div>
              <p className="text-sm text-muted-foreground">Skor Kelengkapan Data</p>
              <p className="text-2xl font-bold">{skorKelengkapan}%</p>
              <p className="text-sm text-muted-foreground mt-1">Status: {statusKelengkapan}</p>
            </div>
            <Badge variant="outline">{jumlahDataLengkap} dari {indikatorKelengkapan.length} Bagian Lengkap</Badge>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
            {indikatorKelengkapan.map((item) => (
              <div key={item.label} className="rounded-md border border-border bg-background px-3 py-2 text-sm flex items-center justify-between gap-3">
                <span>{item.label}</span>
                <span className={`text-xs font-semibold ${item.lengkap ? "text-emerald-600" : "text-red-600"}`}>
                  {item.lengkap ? "Lengkap" : "Kosong"}
                </span>
              </div>
            ))}
          </div>
          {dataBelumLengkap.length > 0 && (
            <p className="text-xs text-muted-foreground mt-3">Bagian yang perlu dilengkapi: {dataBelumLengkap.join(", ")}.</p>
          )}
        </div>
      </div>

      <div className={`${activeTab !== "info" && activeTab !== "operasional" ? "" : "hidden"} rounded-xl border border-border bg-card p-4 mb-8 print:hidden`}>
        <div className="flex flex-col lg:flex-row lg:items-center gap-3">
          <div className="flex-1">
            <p className="text-sm font-semibold mb-1">Pencarian Global</p>
            <input
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              placeholder="Cari sekolah, karyawan, bahan, transaksi, omprengan, atau laporan..."
              className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
            />
          </div>
          <div className="flex flex-wrap gap-2 lg:pt-6">
            <Badge variant="outline">{totalDataTampil.toLocaleString("id-ID")} Data Tampil</Badge>
            {searchKeyword && (
              <Button variant="outline" size="sm" onClick={() => setSearchKeyword("")}>Bersihkan Pencarian</Button>
            )}
          </div>
        </div>
      </div>

      <div className={`${activeTab === "operasional" ? "" : "hidden"} rounded-xl border border-border bg-card p-6 mb-8 print:break-inside-avoid`}>
        <SectionHeader
          title="Ringkasan Data Terbaru"
          subtitle="Informasi terakhir yang tercatat dari beberapa modul utama."
        />
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Transaksi Terbaru</p>
            <p className="font-semibold mt-1">{dataTerbaru.transaksi?.kategori || "Belum ada"}</p>
            <p className="text-xs text-muted-foreground mt-1">
              {dataTerbaru.transaksi ? `${dataTerbaru.transaksi.jenis || "-"} • ${formatRp(dataTerbaru.transaksi.jumlah)}` : "Data transaksi belum tersedia"}
            </p>
          </div>
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Bahan Terbaru</p>
            <p className="font-semibold mt-1">{dataTerbaru.bahan?.nama_bahan || "Belum ada"}</p>
            <p className="text-xs text-muted-foreground mt-1">
              {dataTerbaru.bahan ? `${Number(dataTerbaru.bahan.stok || 0).toLocaleString("id-ID")} ${dataTerbaru.bahan.satuan || ""}` : "Data bahan belum tersedia"}
            </p>
          </div>
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Omprengan Terbaru</p>
            <p className="font-semibold mt-1">{dataTerbaru.omprengan?.nama_barang || "Belum ada"}</p>
            <p className="text-xs text-muted-foreground mt-1">
              {dataTerbaru.omprengan ? `${Number(dataTerbaru.omprengan.jumlah || 0).toLocaleString("id-ID")} unit • ${dataTerbaru.omprengan.kondisi || "-"}` : "Data omprengan belum tersedia"}
            </p>
          </div>
          <div className="rounded-lg bg-muted/30 p-4">
            <p className="text-sm text-muted-foreground">Laporan Terbaru</p>
            <p className="font-semibold mt-1">{dataTerbaru.laporan?.tanggal || "Belum ada"}</p>
            <p className="text-xs text-muted-foreground mt-1">
              {dataTerbaru.laporan ? `${dataTerbaru.laporan.status || "-"} • ${Number(dataTerbaru.laporan.jumlah_terdistribusi || 0).toLocaleString("id-ID")} porsi` : "Data laporan belum tersedia"}
            </p>
          </div>
        </div>
      </div>

      <div id="sekolah" className={`${activeTab === "sekolah" ? "" : "hidden"} rounded-xl border border-border bg-card p-6 mb-8 scroll-mt-24 print:break-inside-avoid`}>
        <SectionHeader
          title="Data Sekolah / Penerima"
          subtitle="Daftar sekolah yang terhubung dengan SPPG ini"
          badges={(
            <>
              <Badge>{sekolahList.length} Sekolah</Badge>
              <Badge variant="outline">{totalSiswaSekolah.toLocaleString("id-ID")} Siswa</Badge>
            </>
          )}
        />

        <form onSubmit={handleTambahSekolah} className={`${isAdmin ? "grid" : "hidden"} grid-cols-1 md:grid-cols-4 gap-3 mb-5 print:hidden`}>
          <input name="nama_sekolah" value={formSekolah.nama_sekolah} onChange={handleInput(setFormSekolah)} placeholder="Nama sekolah" className="rounded-md border border-input bg-background px-3 py-2 text-sm" required />
          <input name="jenjang" value={formSekolah.jenjang} onChange={handleInput(setFormSekolah)} placeholder="Jenjang, contoh: SD" className="rounded-md border border-input bg-background px-3 py-2 text-sm" />
          <input name="jumlah_siswa" type="number" value={formSekolah.jumlah_siswa} onChange={handleInput(setFormSekolah)} placeholder="Jumlah siswa" className="rounded-md border border-input bg-background px-3 py-2 text-sm" />
          <Button type="submit" disabled={savingSekolah}><Plus className="w-4 h-4 mr-2" />{savingSekolah ? "Menyimpan..." : "Tambah Sekolah"}</Button>
        </form>

        {sekolahTampil.length === 0 ? (
          <div className="text-center py-10 text-muted-foreground text-sm">Belum ada data sekolah untuk SPPG ini.</div>
        ) : (
          <div className="overflow-x-auto rounded-lg border border-border">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b bg-primary/5">
                  <th className="text-left px-4 py-3 font-semibold">Nama Sekolah</th>
                  <th className="text-left px-4 py-3 font-semibold">Jenjang</th>
                  <th className="text-right px-4 py-3 font-semibold">Jumlah Siswa</th>
                  {isAdmin && <th className="text-center px-4 py-3 font-semibold print:hidden">Aksi</th>}
                </tr>
              </thead>
              <tbody>
                {sekolahTampil.map((item) => (
                  <tr key={item.id} className="border-b last:border-b-0">
                    {editId === item.id ? (
                      <>
                        <td className="px-4 py-3"><input name="nama_sekolah" value={editForm.nama_sekolah} onChange={handleInput(setEditForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td>
                        <td className="px-4 py-3"><input name="jenjang" value={editForm.jenjang} onChange={handleInput(setEditForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td>
                        <td className="px-4 py-3"><input name="jumlah_siswa" type="number" value={editForm.jumlah_siswa} onChange={handleInput(setEditForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-right" /></td>
                        {isAdmin && (<td className="px-4 py-3 print:hidden"><div className="flex items-center justify-center gap-2"><Button size="sm" onClick={() => handleUpdateSekolah(item.id)} disabled={updatingSekolah}><Save className="w-4 h-4 mr-1" />Simpan</Button><Button size="sm" variant="outline" onClick={cancelEditSekolah}><X className="w-4 h-4 mr-1" />Batal</Button></div></td>)}
                      </>
                    ) : (
                      <>
                        <td className="px-4 py-3 font-medium">{item.nama_sekolah || "-"}</td>
                        <td className="px-4 py-3">{item.jenjang || "-"}</td>
                        <td className="px-4 py-3 text-right">{(Number(item.jumlah_siswa) || 0).toLocaleString("id-ID")}</td>
                        {isAdmin && (<td className="px-4 py-3 print:hidden"><div className="flex items-center justify-center gap-2"><Button size="sm" variant="outline" onClick={() => startEditSekolah(item)}><Pencil className="w-4 h-4 mr-1" />Edit</Button><Button size="sm" variant="destructive" onClick={() => handleDeleteSekolah(item.id)}><Trash2 className="w-4 h-4 mr-1" />Hapus</Button></div></td>)}
                      </>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <div id="transaksi" className={`${activeTab === "rekap" ? "" : "hidden"} rounded-xl border border-border bg-card p-6 mb-8 scroll-mt-24 print:break-inside-avoid`}>
        <SectionHeader
          title="Rincian Transaksi Dana"
          subtitle="Data pemasukan dan pengeluaran khusus untuk SPPG ini."
          badges={<Badge variant="outline">{Number(summaryTransaksi.total_transaksi || 0).toLocaleString("id-ID")} Transaksi</Badge>}
        />

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-5">
          <div className="rounded-xl bg-emerald-50 border border-emerald-100 p-4"><p className="text-sm text-emerald-700">Total Pemasukan</p><p className="text-xl font-bold text-emerald-700">{formatRp(summaryTransaksi.total_pemasukan)}</p></div>
          <div className="rounded-xl bg-red-50 border border-red-100 p-4"><p className="text-sm text-red-700">Total Pengeluaran</p><p className="text-xl font-bold text-red-700">{formatRp(summaryTransaksi.total_pengeluaran)}</p></div>
          <div className="rounded-xl bg-primary/5 border border-primary/10 p-4"><p className="text-sm text-primary">Sisa Dana</p><p className="text-xl font-bold text-primary">{formatRp(summaryTransaksi.sisa_dana)}</p></div>
        </div>

        <div className="flex flex-wrap gap-2 mb-4 print:hidden">
          <Button size="sm" variant={filterTransaksi === "semua" ? "default" : "outline"} onClick={() => setFilterTransaksi("semua")}>Semua</Button>
          <Button size="sm" variant={filterTransaksi === "pemasukan" ? "default" : "outline"} onClick={() => setFilterTransaksi("pemasukan")}>Pemasukan</Button>
          <Button size="sm" variant={filterTransaksi === "pengeluaran" ? "default" : "outline"} onClick={() => setFilterTransaksi("pengeluaran")}>Pengeluaran</Button>
        </div>

        {transaksiTampil.length === 0 ? (
          <div className="text-center py-10 text-muted-foreground text-sm">Belum ada transaksi untuk SPPG ini.</div>
        ) : (
          <div className="overflow-x-auto rounded-lg border border-border">
            <table className="w-full text-sm">
              <thead><tr className="border-b bg-primary/5"><th className="text-left px-4 py-3 font-semibold">Tanggal</th><th className="text-left px-4 py-3 font-semibold">Kategori</th><th className="text-left px-4 py-3 font-semibold">Deskripsi</th><th className="text-left px-4 py-3 font-semibold">Supplier</th><th className="text-left px-4 py-3 font-semibold">Jenis</th><th className="text-right px-4 py-3 font-semibold">Jumlah</th></tr></thead>
              <tbody>
                {transaksiTampil.map((item) => (
                  <tr key={item.id} className="border-b last:border-b-0"><td className="px-4 py-3 whitespace-nowrap">{item.tanggal || "-"}</td><td className="px-4 py-3">{item.kategori || "-"}</td><td className="px-4 py-3 max-w-xs"><p className="line-clamp-2">{item.deskripsi || "-"}</p></td><td className="px-4 py-3">{item.supplier || "-"}</td><td className="px-4 py-3"><span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${item.jenis === "Pemasukan" ? "bg-emerald-100 text-emerald-700" : "bg-red-100 text-red-700"}`}>{item.jenis || "-"}</span></td><td className="px-4 py-3 text-right font-semibold">{formatRp(item.jumlah)}</td></tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <div id="karyawan" className={`${activeTab === "karyawan" ? "" : "hidden"} rounded-xl border border-border bg-card p-6 mb-8 scroll-mt-24 print:break-inside-avoid`}>
        <SectionHeader
          title="Data Karyawan"
          subtitle="Daftar karyawan yang bekerja di SPPG ini"
          badges={<><Badge>{karyawanList.length} Karyawan</Badge><Badge variant="outline">Total Gaji {formatRp(totalGajiKaryawan)}</Badge></>}
        />

        <form onSubmit={handleTambahKaryawan} className={`${isAdmin ? "grid" : "hidden"} grid-cols-1 md:grid-cols-6 gap-3 mb-5 print:hidden`}>
          <input name="nama" value={formKaryawan.nama} onChange={handleInput(setFormKaryawan)} placeholder="Nama karyawan" className="rounded-md border border-input bg-background px-3 py-2 text-sm" required />
          <input name="jabatan" value={formKaryawan.jabatan} onChange={handleInput(setFormKaryawan)} placeholder="Jabatan" className="rounded-md border border-input bg-background px-3 py-2 text-sm" />
          <input name="no_hp" value={formKaryawan.no_hp} onChange={handleInput(setFormKaryawan)} placeholder="No HP" className="rounded-md border border-input bg-background px-3 py-2 text-sm" />
          <input name="alamat" value={formKaryawan.alamat} onChange={handleInput(setFormKaryawan)} placeholder="Alamat" className="rounded-md border border-input bg-background px-3 py-2 text-sm" />
          <input name="gaji" type="number" value={formKaryawan.gaji} onChange={handleInput(setFormKaryawan)} placeholder="Gaji" className="rounded-md border border-input bg-background px-3 py-2 text-sm" />
          <select name="status" value={formKaryawan.status} onChange={handleInput(setFormKaryawan)} className="rounded-md border border-input bg-background px-3 py-2 text-sm"><option value="Aktif">Aktif</option><option value="Tidak Aktif">Tidak Aktif</option></select>
          <div className="md:col-span-6"><Button type="submit" disabled={savingKaryawan}><Plus className="w-4 h-4 mr-2" />{savingKaryawan ? "Menyimpan..." : "Tambah Karyawan"}</Button></div>
        </form>

        {karyawanTampil.length === 0 ? (
          <div className="text-center py-10 text-muted-foreground text-sm">Belum ada data karyawan untuk SPPG ini.</div>
        ) : (
          <div className="overflow-x-auto rounded-lg border border-border">
            <table className="w-full text-sm">
              <thead><tr className="border-b bg-primary/5"><th className="text-left px-4 py-3 font-semibold">Nama</th><th className="text-left px-4 py-3 font-semibold">Jabatan</th><th className="text-left px-4 py-3 font-semibold">No HP</th><th className="text-left px-4 py-3 font-semibold">Alamat</th><th className="text-right px-4 py-3 font-semibold">Gaji</th><th className="text-left px-4 py-3 font-semibold">Status</th>{isAdmin && <th className="text-center px-4 py-3 font-semibold print:hidden">Aksi</th>}</tr></thead>
              <tbody>
                {karyawanTampil.map((item) => (
                  <tr key={item.id} className="border-b last:border-b-0">
                    {editKaryawanId === item.id ? (
                      <>
                        <td className="px-4 py-3"><input name="nama" value={editKaryawanForm.nama} onChange={handleInput(setEditKaryawanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td>
                        <td className="px-4 py-3"><input name="jabatan" value={editKaryawanForm.jabatan} onChange={handleInput(setEditKaryawanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td>
                        <td className="px-4 py-3"><input name="no_hp" value={editKaryawanForm.no_hp} onChange={handleInput(setEditKaryawanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td>
                        <td className="px-4 py-3"><input name="alamat" value={editKaryawanForm.alamat} onChange={handleInput(setEditKaryawanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td>
                        <td className="px-4 py-3"><input name="gaji" type="number" value={editKaryawanForm.gaji} onChange={handleInput(setEditKaryawanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-right" /></td>
                        <td className="px-4 py-3"><select name="status" value={editKaryawanForm.status} onChange={handleInput(setEditKaryawanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"><option value="Aktif">Aktif</option><option value="Tidak Aktif">Tidak Aktif</option></select></td>
                        {isAdmin && (<td className="px-4 py-3 print:hidden"><div className="flex items-center justify-center gap-2"><Button size="sm" onClick={() => handleUpdateKaryawan(item.id)} disabled={updatingKaryawan}><Save className="w-4 h-4 mr-1" />Simpan</Button><Button size="sm" variant="outline" onClick={cancelEditKaryawan}><X className="w-4 h-4 mr-1" />Batal</Button></div></td>)}
                      </>
                    ) : (
                      <>
                        <td className="px-4 py-3 font-medium">{item.nama || "-"}</td><td className="px-4 py-3">{item.jabatan || "-"}</td><td className="px-4 py-3">{item.no_hp || "-"}</td><td className="px-4 py-3 max-w-xs"><p className="line-clamp-2">{item.alamat || "-"}</p></td><td className="px-4 py-3 text-right font-semibold">{formatRp(item.gaji)}</td><td className="px-4 py-3"><span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${statusClass(item.status)}`}>{item.status || "-"}</span></td>{isAdmin && (<td className="px-4 py-3 print:hidden"><div className="flex items-center justify-center gap-2"><Button size="sm" variant="outline" onClick={() => startEditKaryawan(item)}><Pencil className="w-4 h-4 mr-1" />Edit</Button><Button size="sm" variant="destructive" onClick={() => handleDeleteKaryawan(item.id)}><Trash2 className="w-4 h-4 mr-1" />Hapus</Button></div></td>)}
                      </>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      <div id="bahan" className={`${activeTab === "bahan" ? "" : "hidden"} rounded-xl border border-border bg-card p-6 mb-8 scroll-mt-24 print:break-inside-avoid`}>
        <SectionHeader title="Data Bahan Makanan" subtitle="Daftar stok bahan makanan untuk operasional dapur SPPG ini" badges={<><Badge>{bahanList.length} Bahan</Badge><Badge variant="outline">Nilai Stok {formatRp(totalNilaiBahan)}</Badge></>} />
        <form onSubmit={handleTambahBahan} className={`${isAdmin ? "grid" : "hidden"} grid-cols-1 md:grid-cols-7 gap-3 mb-5 print:hidden`}>
          <input name="nama_bahan" value={formBahan.nama_bahan} onChange={handleInput(setFormBahan)} placeholder="Nama bahan" className="rounded-md border border-input bg-background px-3 py-2 text-sm" required />
          <input name="kategori" value={formBahan.kategori} onChange={handleInput(setFormBahan)} placeholder="Kategori" className="rounded-md border border-input bg-background px-3 py-2 text-sm" />
          <input name="satuan" value={formBahan.satuan} onChange={handleInput(setFormBahan)} placeholder="Satuan" className="rounded-md border border-input bg-background px-3 py-2 text-sm" />
          <input name="stok" type="number" value={formBahan.stok} onChange={handleInput(setFormBahan)} placeholder="Stok" className="rounded-md border border-input bg-background px-3 py-2 text-sm" />
          <input name="harga_satuan" type="number" value={formBahan.harga_satuan} onChange={handleInput(setFormBahan)} placeholder="Harga satuan" className="rounded-md border border-input bg-background px-3 py-2 text-sm" />
          <input name="tanggal_masuk" type="date" value={formBahan.tanggal_masuk} onChange={handleInput(setFormBahan)} className="rounded-md border border-input bg-background px-3 py-2 text-sm" />
          <Button type="submit" disabled={savingBahan}><Plus className="w-4 h-4 mr-2" />{savingBahan ? "Menyimpan..." : "Tambah Bahan"}</Button>
        </form>
        <div className="flex flex-wrap gap-2 mb-4 print:hidden"><Button size="sm" variant={filterBahan === "semua" ? "default" : "outline"} onClick={() => setFilterBahan("semua")}>Semua</Button><Button size="sm" variant={filterBahan === "stok_rendah" ? "default" : "outline"} onClick={() => setFilterBahan("stok_rendah")}>Stok Rendah</Button><Button size="sm" variant={filterBahan === "stok_habis" ? "default" : "outline"} onClick={() => setFilterBahan("stok_habis")}>Stok Habis</Button></div>
        {bahanTampil.length === 0 ? (
          <div className="text-center py-10 text-muted-foreground text-sm">Belum ada data bahan makanan untuk SPPG ini.</div>
        ) : (
          <div className="overflow-x-auto rounded-lg border border-border"><table className="w-full text-sm"><thead><tr className="border-b bg-primary/5"><th className="text-left px-4 py-3 font-semibold">Nama Bahan</th><th className="text-left px-4 py-3 font-semibold">Kategori</th><th className="text-left px-4 py-3 font-semibold">Satuan</th><th className="text-right px-4 py-3 font-semibold">Stok</th><th className="text-right px-4 py-3 font-semibold">Harga Satuan</th><th className="text-right px-4 py-3 font-semibold">Total Nilai</th><th className="text-left px-4 py-3 font-semibold">Tanggal Masuk</th>{isAdmin && <th className="text-center px-4 py-3 font-semibold print:hidden">Aksi</th>}</tr></thead><tbody>{bahanTampil.map((item) => { const totalNilai = Number(item.total_nilai) || (Number(item.stok) || 0) * (Number(item.harga_satuan) || 0); return (<tr key={item.id} className="border-b last:border-b-0">{editBahanId === item.id ? (<><td className="px-4 py-3"><input name="nama_bahan" value={editBahanForm.nama_bahan} onChange={handleInput(setEditBahanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td><td className="px-4 py-3"><input name="kategori" value={editBahanForm.kategori} onChange={handleInput(setEditBahanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td><td className="px-4 py-3"><input name="satuan" value={editBahanForm.satuan} onChange={handleInput(setEditBahanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td><td className="px-4 py-3"><input name="stok" type="number" value={editBahanForm.stok} onChange={handleInput(setEditBahanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-right" /></td><td className="px-4 py-3"><input name="harga_satuan" type="number" value={editBahanForm.harga_satuan} onChange={handleInput(setEditBahanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-right" /></td><td className="px-4 py-3 text-right font-semibold">{formatRp((Number(editBahanForm.stok) || 0) * (Number(editBahanForm.harga_satuan) || 0))}</td><td className="px-4 py-3"><input name="tanggal_masuk" type="date" value={editBahanForm.tanggal_masuk} onChange={handleInput(setEditBahanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td>{isAdmin && (<td className="px-4 py-3 print:hidden"><div className="flex items-center justify-center gap-2"><Button size="sm" onClick={() => handleUpdateBahan(item.id)} disabled={updatingBahan}><Save className="w-4 h-4 mr-1" />Simpan</Button><Button size="sm" variant="outline" onClick={cancelEditBahan}><X className="w-4 h-4 mr-1" />Batal</Button></div></td>)}</>) : (<><td className="px-4 py-3 font-medium">{item.nama_bahan || "-"}</td><td className="px-4 py-3">{item.kategori || "-"}</td><td className="px-4 py-3">{item.satuan || "-"}</td><td className="px-4 py-3 text-right">{(Number(item.stok) || 0).toLocaleString("id-ID")}</td><td className="px-4 py-3 text-right">{formatRp(item.harga_satuan)}</td><td className="px-4 py-3 text-right font-semibold">{formatRp(totalNilai)}</td><td className="px-4 py-3 whitespace-nowrap">{item.tanggal_masuk || "-"}</td>{isAdmin && (<td className="px-4 py-3 print:hidden"><div className="flex items-center justify-center gap-2"><Button size="sm" variant="outline" onClick={() => startEditBahan(item)}><Pencil className="w-4 h-4 mr-1" />Edit</Button><Button size="sm" variant="destructive" onClick={() => handleDeleteBahan(item.id)}><Trash2 className="w-4 h-4 mr-1" />Hapus</Button></div></td>)}</>)}</tr>); })}</tbody></table></div>
        )}
      </div>

      <div id="omprengan" className={`${activeTab === "omprengan" ? "" : "hidden"} rounded-xl border border-border bg-card p-6 mb-8 scroll-mt-24 print:break-inside-avoid`}>
        <SectionHeader title="Data Omprengan / Peralatan Makan" subtitle="Daftar omprengan dan peralatan makan yang digunakan oleh SPPG ini" badges={<><Badge>{omprenganList.length} Jenis Barang</Badge><Badge variant="outline">Total {totalOmprengan} Unit</Badge></>} />
        <form onSubmit={handleTambahOmprengan} className={`${isAdmin ? "grid" : "hidden"} grid-cols-1 md:grid-cols-6 gap-3 mb-5 print:hidden`}>
          <input name="nama_barang" value={formOmprengan.nama_barang} onChange={handleInput(setFormOmprengan)} placeholder="Nama barang" className="rounded-md border border-input bg-background px-3 py-2 text-sm" required />
          <input name="kategori" value={formOmprengan.kategori} onChange={handleInput(setFormOmprengan)} placeholder="Kategori" className="rounded-md border border-input bg-background px-3 py-2 text-sm" />
          <input name="jumlah" type="number" value={formOmprengan.jumlah} onChange={handleInput(setFormOmprengan)} placeholder="Jumlah" className="rounded-md border border-input bg-background px-3 py-2 text-sm" />
          <select name="kondisi" value={formOmprengan.kondisi} onChange={handleInput(setFormOmprengan)} className="rounded-md border border-input bg-background px-3 py-2 text-sm"><option value="Baik">Baik</option><option value="Rusak Ringan">Rusak Ringan</option><option value="Rusak Berat">Rusak Berat</option><option value="Hilang">Hilang</option></select>
          <input name="keterangan" value={formOmprengan.keterangan} onChange={handleInput(setFormOmprengan)} placeholder="Keterangan" className="rounded-md border border-input bg-background px-3 py-2 text-sm" />
          <Button type="submit" disabled={savingOmprengan}><Plus className="w-4 h-4 mr-2" />{savingOmprengan ? "Menyimpan..." : "Tambah Omprengan"}</Button>
        </form>
        <div className="flex flex-wrap gap-2 mb-4 print:hidden"><Button size="sm" variant={filterOmprengan === "semua" ? "default" : "outline"} onClick={() => setFilterOmprengan("semua")}>Semua</Button><Button size="sm" variant={filterOmprengan === "baik" ? "default" : "outline"} onClick={() => setFilterOmprengan("baik")}>Baik</Button><Button size="sm" variant={filterOmprengan === "bermasalah" ? "default" : "outline"} onClick={() => setFilterOmprengan("bermasalah")}>Bermasalah</Button></div>
        {omprenganTampil.length === 0 ? <div className="text-center py-10 text-muted-foreground text-sm">Belum ada data omprengan untuk SPPG ini.</div> : <div className="overflow-x-auto rounded-lg border border-border"><table className="w-full text-sm"><thead><tr className="border-b bg-primary/5"><th className="text-left px-4 py-3 font-semibold">Nama Barang</th><th className="text-left px-4 py-3 font-semibold">Kategori</th><th className="text-right px-4 py-3 font-semibold">Jumlah</th><th className="text-left px-4 py-3 font-semibold">Kondisi</th><th className="text-left px-4 py-3 font-semibold">Keterangan</th>{isAdmin && <th className="text-center px-4 py-3 font-semibold print:hidden">Aksi</th>}</tr></thead><tbody>{omprenganTampil.map((item) => (<tr key={item.id} className="border-b last:border-b-0">{editOmprenganId === item.id ? (<><td className="px-4 py-3"><input name="nama_barang" value={editOmprenganForm.nama_barang} onChange={handleInput(setEditOmprenganForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td><td className="px-4 py-3"><input name="kategori" value={editOmprenganForm.kategori} onChange={handleInput(setEditOmprenganForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td><td className="px-4 py-3"><input name="jumlah" type="number" value={editOmprenganForm.jumlah} onChange={handleInput(setEditOmprenganForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-right" /></td><td className="px-4 py-3"><select name="kondisi" value={editOmprenganForm.kondisi} onChange={handleInput(setEditOmprenganForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"><option value="Baik">Baik</option><option value="Rusak Ringan">Rusak Ringan</option><option value="Rusak Berat">Rusak Berat</option><option value="Hilang">Hilang</option></select></td><td className="px-4 py-3"><input name="keterangan" value={editOmprenganForm.keterangan} onChange={handleInput(setEditOmprenganForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td>{isAdmin && (<td className="px-4 py-3 print:hidden"><div className="flex items-center justify-center gap-2"><Button size="sm" onClick={() => handleUpdateOmprengan(item.id)} disabled={updatingOmprengan}><Save className="w-4 h-4 mr-1" />Simpan</Button><Button size="sm" variant="outline" onClick={cancelEditOmprengan}><X className="w-4 h-4 mr-1" />Batal</Button></div></td>)}</>) : (<><td className="px-4 py-3 font-medium">{item.nama_barang || "-"}</td><td className="px-4 py-3">{item.kategori || "-"}</td><td className="px-4 py-3 text-right font-semibold">{(Number(item.jumlah) || 0).toLocaleString("id-ID")}</td><td className="px-4 py-3"><span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${statusClass(item.kondisi)}`}>{item.kondisi || "-"}</span></td><td className="px-4 py-3 max-w-xs"><p className="line-clamp-2">{item.keterangan || "-"}</p></td>{isAdmin && (<td className="px-4 py-3 print:hidden"><div className="flex items-center justify-center gap-2"><Button size="sm" variant="outline" onClick={() => startEditOmprengan(item)}><Pencil className="w-4 h-4 mr-1" />Edit</Button><Button size="sm" variant="destructive" onClick={() => handleDeleteOmprengan(item.id)}><Trash2 className="w-4 h-4 mr-1" />Hapus</Button></div></td>)}</>)}</tr>))}</tbody></table></div>}
      </div>

      <div id="laporan" className={`${activeTab === "laporan" ? "" : "hidden"} rounded-xl border border-border bg-card p-6 mb-8 scroll-mt-24 print:break-inside-avoid`}>
        <SectionHeader title="Laporan Operasional Dapur" subtitle="Catatan harian menu, jumlah porsi, distribusi, kendala, dan status operasional" badges={<><Badge>{laporanList.length} Laporan</Badge><Badge variant="outline">{totalTerdistribusiLaporan.toLocaleString("id-ID")} / {totalPorsiLaporan.toLocaleString("id-ID")} Porsi</Badge></>} />
        <form onSubmit={handleTambahLaporan} className={`${isAdmin ? "grid" : "hidden"} grid-cols-1 md:grid-cols-8 gap-3 mb-5 print:hidden`}><input name="tanggal" type="date" value={formLaporan.tanggal} onChange={handleInput(setFormLaporan)} className="rounded-md border border-input bg-background px-3 py-2 text-sm" required /><input name="menu_makanan" value={formLaporan.menu_makanan} onChange={handleInput(setFormLaporan)} placeholder="Menu makanan" className="rounded-md border border-input bg-background px-3 py-2 text-sm" /><input name="jumlah_porsi" type="number" value={formLaporan.jumlah_porsi} onChange={handleInput(setFormLaporan)} placeholder="Jumlah porsi" className="rounded-md border border-input bg-background px-3 py-2 text-sm" /><input name="jumlah_terdistribusi" type="number" value={formLaporan.jumlah_terdistribusi} onChange={handleInput(setFormLaporan)} placeholder="Terdistribusi" className="rounded-md border border-input bg-background px-3 py-2 text-sm" /><input name="kendala" value={formLaporan.kendala} onChange={handleInput(setFormLaporan)} placeholder="Kendala" className="rounded-md border border-input bg-background px-3 py-2 text-sm" /><input name="catatan" value={formLaporan.catatan} onChange={handleInput(setFormLaporan)} placeholder="Catatan" className="rounded-md border border-input bg-background px-3 py-2 text-sm" /><select name="status" value={formLaporan.status} onChange={handleInput(setFormLaporan)} className="rounded-md border border-input bg-background px-3 py-2 text-sm"><option value="Draft">Draft</option><option value="Selesai">Selesai</option></select><Button type="submit" disabled={savingLaporan}><Plus className="w-4 h-4 mr-2" />{savingLaporan ? "Menyimpan..." : "Tambah Laporan"}</Button></form>
        <div className="flex flex-wrap gap-2 mb-4 print:hidden"><Button size="sm" variant={filterLaporan === "semua" ? "default" : "outline"} onClick={() => setFilterLaporan("semua")}>Semua</Button><Button size="sm" variant={filterLaporan === "draft" ? "default" : "outline"} onClick={() => setFilterLaporan("draft")}>Draft</Button><Button size="sm" variant={filterLaporan === "selesai" ? "default" : "outline"} onClick={() => setFilterLaporan("selesai")}>Selesai</Button><Button size="sm" variant={filterLaporan === "ada_kendala" ? "default" : "outline"} onClick={() => setFilterLaporan("ada_kendala")}>Ada Kendala</Button></div>
        {laporanTampil.length === 0 ? <div className="text-center py-10 text-muted-foreground text-sm">Belum ada laporan operasional untuk SPPG ini.</div> : <div className="overflow-x-auto rounded-lg border border-border"><table className="w-full text-sm"><thead><tr className="border-b bg-primary/5"><th className="text-left px-4 py-3 font-semibold">Tanggal</th><th className="text-left px-4 py-3 font-semibold">Menu</th><th className="text-right px-4 py-3 font-semibold">Porsi</th><th className="text-right px-4 py-3 font-semibold">Terdistribusi</th><th className="text-left px-4 py-3 font-semibold">Kendala</th><th className="text-left px-4 py-3 font-semibold">Catatan</th><th className="text-left px-4 py-3 font-semibold">Status</th>{isAdmin && <th className="text-center px-4 py-3 font-semibold print:hidden">Aksi</th>}</tr></thead><tbody>{laporanTampil.map((item) => (<tr key={item.id} className="border-b last:border-b-0">{editLaporanId === item.id ? (<><td className="px-4 py-3"><input name="tanggal" type="date" value={editLaporanForm.tanggal} onChange={handleInput(setEditLaporanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td><td className="px-4 py-3"><input name="menu_makanan" value={editLaporanForm.menu_makanan} onChange={handleInput(setEditLaporanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td><td className="px-4 py-3"><input name="jumlah_porsi" type="number" value={editLaporanForm.jumlah_porsi} onChange={handleInput(setEditLaporanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-right" /></td><td className="px-4 py-3"><input name="jumlah_terdistribusi" type="number" value={editLaporanForm.jumlah_terdistribusi} onChange={handleInput(setEditLaporanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm text-right" /></td><td className="px-4 py-3"><input name="kendala" value={editLaporanForm.kendala} onChange={handleInput(setEditLaporanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td><td className="px-4 py-3"><input name="catatan" value={editLaporanForm.catatan} onChange={handleInput(setEditLaporanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm" /></td><td className="px-4 py-3"><select name="status" value={editLaporanForm.status} onChange={handleInput(setEditLaporanForm)} className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm"><option value="Draft">Draft</option><option value="Selesai">Selesai</option></select></td>{isAdmin && (<td className="px-4 py-3 print:hidden"><div className="flex items-center justify-center gap-2"><Button size="sm" onClick={() => handleUpdateLaporan(item.id)} disabled={updatingLaporan}><Save className="w-4 h-4 mr-1" />Simpan</Button><Button size="sm" variant="outline" onClick={cancelEditLaporan}><X className="w-4 h-4 mr-1" />Batal</Button></div></td>)}</>) : (<><td className="px-4 py-3 whitespace-nowrap">{item.tanggal || "-"}</td><td className="px-4 py-3 max-w-xs"><p className="line-clamp-2">{item.menu_makanan || "-"}</p></td><td className="px-4 py-3 text-right">{(Number(item.jumlah_porsi) || 0).toLocaleString("id-ID")}</td><td className="px-4 py-3 text-right font-semibold">{(Number(item.jumlah_terdistribusi) || 0).toLocaleString("id-ID")}</td><td className="px-4 py-3 max-w-xs"><p className="line-clamp-2">{item.kendala || "-"}</p></td><td className="px-4 py-3 max-w-xs"><p className="line-clamp-2">{item.catatan || "-"}</p></td><td className="px-4 py-3"><span className={`px-2 py-0.5 rounded-full text-xs font-semibold ${statusClass(item.status)}`}>{item.status || "-"}</span></td>{isAdmin && (<td className="px-4 py-3 print:hidden"><div className="flex items-center justify-center gap-2"><Button size="sm" variant="outline" onClick={() => startEditLaporan(item)}><Pencil className="w-4 h-4 mr-1" />Edit</Button><Button size="sm" variant="destructive" onClick={() => handleDeleteLaporan(item.id)}><Trash2 className="w-4 h-4 mr-1" />Hapus</Button></div></td>)}</>)}</tr>))}</tbody></table></div>}
      </div>
      <div className={`${isAdmin ? "flex" : "hidden"} flex-wrap gap-3 print:hidden`}>
        <Link to="/admin/sppg"><Button variant="outline">Kelola Data SPPG</Button></Link>
        <Link to={`/admin/sppg/edit/${sppg.id}`}><Button>Edit Data</Button></Link>
      </div>
    </div>
  );
}
