import { useEffect, useState } from "react";
import { api } from "@/services/api";
import { Plus, Trash2, Upload, Save, Send } from "lucide-react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { useAuditLog } from "../../hooks/useAuditLog";
import { useNotifications } from "../../hooks/useNotifications";

const defaultBahan = () => ({
  nama: "",
  nama_bahan: "",
  jumlah: "",
  satuan: "kg",
  harga: "",
  harga_satuan: "",
  total: 0,
});

const API_BASE = "http://localhost/backend";
const TRACKING_CREATE_API = `${API_BASE}/api/tracking/create.php`;
const TRACKING_FORM_DATA_API = `${API_BASE}/api/tracking/form-data.php`;
const TRACKING_UPLOAD_BUKTI_API = `${API_BASE}/api/tracking/upload-bukti-sppg.php`;
const MENU_HARIAN_SUBMIT_API = `${API_BASE}/api/menu-harian/submit.php`;
const PUSKESMAS_API = `${API_BASE}/api/puskesmas/list.php`;

export default function SPPGSaya() {
  const { addLog } = useAuditLog();
  const { addNotification } = useNotifications();

  const [form, setForm] = useState({
    tanggal: new Date().toISOString().split("T")[0],
    waktu: "pagi",
    kategori: "Siswa",
    menu_nasi: "Nasi Putih",
    menu_lauk: "",
    menu_sayur: "",
    menu_buah: "",
    menu_susu: "",
    dana_total: "",
    dana_per_omprengan: "",
    kalori: "",
    protein: "",
    karbohidrat: "",
    lemak: "",
    serat: "",
    zat_besi: "",
    kalsium: "",
    vitamin: "",
    catatan_gizi: "",
    catatan: "",
    lokasi: "",
    lokasi_mbg_tipe: "sekolah",
    sekolah_id: "",
    puskesmas_id: "",
    puskesmas_nama: "",
    puskesmas_daerah: "",
    jumlah_omprengan: "",
    nama_kurir: "",
    kendaraan: "Mobil MBG",
    plat_nomor: "",
    status: "draft",
  });

  const [bahanList, setBahanList] = useState([defaultBahan()]);
  const [fotoBahan, setFotoBahan] = useState(null);
  const [fotoMakanan, setFotoMakanan] = useState(null);
  const [fotoBahanFile, setFotoBahanFile] = useState(null);
  const [fotoMakananFile, setFotoMakananFile] = useState(null);
  const [sppgData, setSppgData] = useState(null);
  const [sekolahList, setSekolahList] = useState([]);
  const [puskesmasList, setPuskesmasList] = useState([]);
  const [loadingSekolah, setLoadingSekolah] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  const hitungTotalBahan = (item) => {
    const jumlah = Number(item.jumlah) || 0;
    const harga = Number(item.harga_satuan || item.harga) || 0;

    return jumlah * harga;
  };

  const updateBahan = (idx, field, val) => {
    setBahanList((prev) =>
      prev.map((b, i) => {
        if (i !== idx) return b;

        const updated = { ...b, [field]: val };

        if (field === "nama") {
          updated.nama_bahan = val;
        }

        if (field === "nama_bahan") {
          updated.nama = val;
        }

        if (field === "harga") {
          updated.harga_satuan = val;
        }

        if (field === "harga_satuan") {
          updated.harga = val;
        }

        updated.total = hitungTotalBahan(updated);

        return updated;
      })
    );
  };

  const totalBahan = bahanList.reduce(
    (acc, b) => acc + (Number(b.total) || 0),
    0
  );

  const getSppgId = () => {
    return (
      localStorage.getItem("sppg_id") ||
      localStorage.getItem("user_sppg_id") ||
      localStorage.getItem("sppgId") ||
      ""
    );
  };

  const loadSppgFormData = async () => {
    const sppgId = getSppgId();

    if (!sppgId) return;

    try {
      setLoadingSekolah(true);

      const data = await fetchJsonSafe(
        `${TRACKING_FORM_DATA_API}?sppg_id=${sppgId}`,
        {},
        "API data SPPG/sekolah"
      );

      if (!data.success) {
        console.warn(data.message || "Gagal mengambil data SPPG");
        setSekolahList([]);
        return;
      }

      setSppgData(data.data?.sppg || null);
      setSekolahList(Array.isArray(data.data?.sekolah) ? data.data.sekolah : []);

      const puskesmasData = await fetchJsonSafe(
        `${PUSKESMAS_API}?sppg_id=${sppgId}`,
        {},
        "API data puskesmas"
      );

      setPuskesmasList(
        puskesmasData.success && Array.isArray(puskesmasData.data)
          ? puskesmasData.data
          : []
      );
    } catch (err) {
      console.error("Gagal mengambil data SPPG/sekolah/puskesmas:", err);
      setSekolahList([]);
      setPuskesmasList([]);
    } finally {
      setLoadingSekolah(false);
    }
  };

  useEffect(() => {
    loadSppgFormData();
  }, []);

  const selectedSekolah = sekolahList.find(
    (item) => String(item.id) === String(form.sekolah_id)
  );

  const selectedPuskesmas = puskesmasList.find(
    (item) => String(item.id) === String(form.puskesmas_id)
  );

  const fetchJsonSafe = async (url, options = {}, label = "endpoint") => {
    let res;

    try {
      res = await fetch(url, options);
    } catch (err) {
      throw new Error(
        `Gagal menghubungi ${label}. Cek apakah backend XAMPP aktif dan URL ini bisa dibuka: ${url}`
      );
    }

    let data;

    try {
      data = await res.json();
    } catch (err) {
      throw new Error(
        `${label} tidak mengembalikan JSON valid. Biasanya ada error PHP di endpoint ini: ${url}`
      );
    }

    if (!res.ok) {
      throw new Error(data.message || `${label} gagal dengan HTTP ${res.status}`);
    }

    return data;
  };

  const uploadBuktiTracking = async (trackingId) => {
    if (!trackingId || (!fotoBahanFile && !fotoMakananFile)) return;

    const formData = new FormData();
    formData.append("id", trackingId);

    if (fotoBahanFile) {
      formData.append("foto_omprengan", fotoBahanFile);
    }

    if (fotoMakananFile) {
      formData.append("foto_menu", fotoMakananFile);
    }

    const data = await fetchJsonSafe(
      TRACKING_UPLOAD_BUKTI_API,
      {
        method: "POST",
        body: formData,
      },
      "API upload bukti tracking"
    );

    if (!data.success) {
      throw new Error(data.message || "Gagal upload bukti ke tracking");
    }
  };


  const handleFileUpload = async (file, setter) => {
    if (!file) return;

    const formData = new FormData();
    formData.append("foto", file);

    try {
      setUploading(true);

      const data = await fetchJsonSafe(
        `${API_BASE}/api/upload_foto_omprengan.php`,
        {
          method: "POST",
          body: formData,
        },
        "API upload foto omprengan"
      );

      if (!data.success) {
        alert(data.message || "Upload foto gagal");
        return;
      }

      // data.data.url contoh:
      // http://localhost/backend/uploads/omprengan/nama_file.jpg
      setter(data.data.url);
    } catch (err) {
      console.error(err);
      alert("Tidak bisa terhubung ke server upload.");
    } finally {
      setUploading(false);
    }
  };

  const submitMenuHarian = async (status, sppgId) => {
    const menuItems = [
      form.menu_nasi,
      form.menu_lauk,
      form.menu_sayur,
      form.menu_buah,
      form.menu_susu,
    ].filter((item) => String(item || "").trim() !== "");

    const bahanPayload = bahanList
      .map((item) => {
        const jumlah = Number(item.jumlah) || 0;
        const hargaSatuan = Number(item.harga_satuan || item.harga) || 0;
        const total = Number(item.total) || jumlah * hargaSatuan;

        return {
          nama: item.nama_bahan || item.nama || "",
          nama_bahan: item.nama_bahan || item.nama || "",
          jumlah,
          satuan: item.satuan || "",
          harga: hargaSatuan,
          harga_satuan: hargaSatuan,
          total,
          kategori: form.kategori || "Siswa",
        };
      })
      .filter((item) => item.nama_bahan.trim() !== "");

    const data = await fetchJsonSafe(
      MENU_HARIAN_SUBMIT_API,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          sppg_id: Number(sppgId),
          tanggal: form.tanggal,
          waktu: form.waktu,
          kategori: form.kategori || "Siswa",
          lokasi_mbg_tipe: form.lokasi_mbg_tipe || "sekolah",
          lokasi:
            form.lokasi_mbg_tipe === "puskesmas"
              ? `${form.puskesmas_nama} - ${form.puskesmas_daerah}`
              : form.lokasi,
          puskesmas_id:
            form.lokasi_mbg_tipe === "puskesmas" && form.puskesmas_id
              ? Number(form.puskesmas_id)
              : null,
          puskesmas_nama:
            form.lokasi_mbg_tipe === "puskesmas" ? form.puskesmas_nama : "",
          puskesmas_daerah:
            form.lokasi_mbg_tipe === "puskesmas" ? form.puskesmas_daerah : "",
          status,
          catatan: form.catatan,
          dana_total: Number(form.dana_total) || 0,
          dana_per_omprengan: Number(form.dana_per_omprengan) || 0,
          kalori: Number(form.kalori) || 0,
          protein: Number(form.protein) || 0,
          karbohidrat: Number(form.karbohidrat) || 0,
          lemak: Number(form.lemak) || 0,
          serat: Number(form.serat) || 0,
          zat_besi: Number(form.zat_besi) || 0,
          kalsium: Number(form.kalsium) || 0,
          vitamin: form.vitamin || "",
          catatan_gizi: form.catatan_gizi || "",
          bahan: bahanPayload,
          total_bahan: bahanPayload.reduce((acc, item) => acc + Number(item.total || 0), 0),
          menu_items: menuItems,
          foto_bahan_url: fotoBahan || "",
          foto_makanan_url: fotoMakanan || "",
          sekolah_id:
            form.lokasi_mbg_tipe === "sekolah" && form.sekolah_id
              ? Number(form.sekolah_id)
              : null,
          jumlah_omprengan: Number(form.jumlah_omprengan) || 0,
        }),
      },
      "API simpan menu harian"
    );

    if (!data.success) {
      throw new Error(data.message || "Gagal menyimpan menu harian.");
    }

    return data.data;
  };

  const handleSubmit = async (status) => {
    if (submitting) return;

    try {
      setSubmitting(true);

      const sppgId = getSppgId();

      if (!sppgId) {
        alert("ID SPPG belum ditemukan. Pastikan akun SPPG sudah login dan terhubung ke data SPPG.");
        return;
      }

      if (status === "menunggu_validasi") {
        if (!form.kategori) {
          alert("Pilih kategori penerima dulu.");
          return;
        }

        if (form.lokasi_mbg_tipe === "sekolah" && !form.sekolah_id) {
          alert("Pilih sekolah tujuan dulu.");
          return;
        }

        if (form.lokasi_mbg_tipe === "puskesmas" && !form.puskesmas_id && !form.puskesmas_nama.trim()) {
          alert("Pilih puskesmas dulu.");
          return;
        }

        if (!form.jumlah_omprengan || Number(form.jumlah_omprengan) <= 0) {
          alert("Isi jumlah omprengan dulu.");
          return;
        }

        if (!form.nama_kurir.trim()) {
          alert("Isi nama kurir/sopir dulu.");
          return;
        }

        if (!form.plat_nomor.trim()) {
          alert("Isi plat nomor kendaraan dulu.");
          return;
        }

        if (!fotoBahanFile || !fotoMakananFile) {
          alert("Upload foto bahan/omprengan dan foto menu makanan jadi dulu.");
          return;
        }
      }

      const payload = {
        ...form,
        status,
        bahan_json: JSON.stringify(
          bahanList.map((item) => {
            const jumlah = Number(item.jumlah) || 0;
            const hargaSatuan = Number(item.harga_satuan || item.harga) || 0;
            return {
              ...item,
              nama_bahan: item.nama_bahan || item.nama || "",
              harga_satuan: hargaSatuan,
              total: Number(item.total) || jumlah * hargaSatuan,
              kategori: form.kategori || "Siswa",
            };
          })
        ),
        total_bahan: totalBahan,
        kalori: Number(form.kalori) || 0,
        protein: Number(form.protein) || 0,
        karbohidrat: Number(form.karbohidrat) || 0,
        lemak: Number(form.lemak) || 0,
        serat: Number(form.serat) || 0,
        zat_besi: Number(form.zat_besi) || 0,
        kalsium: Number(form.kalsium) || 0,
        vitamin: form.vitamin || "",
        catatan_gizi: form.catatan_gizi || "",
        foto_bahan_url: fotoBahan || "",
        foto_makanan_url: fotoMakanan || "",
      };

      console.log("Payload laporan SPPG:", payload);

      await submitMenuHarian(status, sppgId);

      try {
        await api.create("Transaksi", {
          sppg_id: sppgId,
          tanggal: form.tanggal,
          kategori: "Bahan Pokok",
          deskripsi: `Kategori: ${form.kategori || "Siswa"} | Lokasi MBG: ${form.lokasi_mbg_tipe === "puskesmas" ? `${form.puskesmas_nama} - ${form.puskesmas_daerah}` : "Sekolah"} | Menu: ${form.menu_nasi}, ${form.menu_lauk}, ${form.menu_sayur}, ${form.menu_buah}, ${form.menu_susu}, Status: ${status}`,
          jumlah: totalBahan,
        });
      } catch (err) {
        console.warn("Transaksi lokal gagal disimpan, tetapi menu harian/tracking tetap lanjut:", err);
      }

      let trackingResult = null;

      if (status === "menunggu_validasi" && form.lokasi_mbg_tipe === "sekolah") {
        trackingResult = await fetchJsonSafe(
          TRACKING_CREATE_API,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              sppg_id: Number(sppgId),
              sekolah_id: Number(form.sekolah_id),
              jumlah_omprengan: Number(form.jumlah_omprengan) || 0,
              nama_kurir: form.nama_kurir,
              kendaraan: form.kendaraan,
              plat_nomor: form.plat_nomor,
              catatan_sppg: form.catatan,
            }),
          },
          "API buat tracking pengiriman"
        );

        if (!trackingResult.success) {
          alert(trackingResult.message || "Gagal membuat data tracking pengiriman.");
          return;
        }

        await uploadBuktiTracking(trackingResult.data?.id);
      }

      addLog({
        actor: "Operator SPPG",
        action: `Submit laporan harian ${form.kategori || "Siswa"} (${status})`,
        target: `Tanggal ${form.tanggal}`,
        role: "sppg",
      });

      if (status === "menunggu_validasi") {
        addNotification({
          title: "Laporan Dikirim",
          message: `Laporan harian ${form.kategori || "Siswa"} tanggal ${form.tanggal} sudah masuk dan menunggu validasi.`,
          type: "info",
        });

        alert(
          form.lokasi_mbg_tipe === "sekolah"
            ? `Berhasil dikirim untuk validasi. Kategori: ${form.kategori || "Siswa"}. Kode konfirmasi: ${
                trackingResult?.data?.kode_konfirmasi || "-"
              }`
            : `Berhasil dikirim untuk validasi. Kategori: ${form.kategori || "Siswa"}. Lokasi MBG: ${form.puskesmas_nama} - ${form.puskesmas_daerah}.`
        );
      }

      setSubmitted(true);
    } catch (err) {
      console.error("Gagal submit laporan:", err);
      alert(err.message || "Tidak bisa mengirim laporan. Cek server backend.");
    } finally {
      setSubmitting(false);
    }
  };

  if (submitted) {
    return (
      <div className="max-w-2xl mx-auto p-8 text-center space-y-4">
        <div className="w-20 h-20 bg-emerald-100 rounded-full flex items-center justify-center mx-auto">
          <Send className="w-10 h-10 text-emerald-600" />
        </div>

        <h2 className="text-2xl font-black text-foreground">
          Laporan Terkirim!
        </h2>

        <p className="text-muted-foreground">
          Laporan harian Anda sudah dikirim dan menunggu validasi dari Validator
          Sekolah.
        </p>

        <Button
          onClick={() => setSubmitted(false)}
          className="rounded-full bg-primary"
        >
          Buat Laporan Baru
        </Button>
      </div>
    );
  }

  return (
    <div className="max-w-4xl mx-auto p-4 sm:p-6 lg:p-8 space-y-6">
      <div>
        <h1 className="text-2xl font-black text-foreground">SPPG Saya</h1>
        <p className="text-sm text-muted-foreground mt-1">
          Input data harian menu makanan, bukti foto omprengan, dan penggunaan
          dana.
        </p>
      </div>

      {/* 1. Informasi Umum */}
      <div className="bg-card rounded-xl border border-border p-5 sm:p-6 space-y-4">
        <h2 className="font-bold text-foreground flex items-center gap-2">
          <span className="w-6 h-6 bg-primary text-primary-foreground rounded-full text-xs flex items-center justify-center font-black">
            1
          </span>
          Informasi Umum
        </h2>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div>
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
              Tanggal
            </label>
            <Input
              type="date"
              value={form.tanggal}
              onChange={(e) =>
                setForm({ ...form, tanggal: e.target.value })
              }
              className="rounded-lg"
            />
          </div>

          <div>
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
              Waktu
            </label>
            <select
              value={form.waktu}
              onChange={(e) => setForm({ ...form, waktu: e.target.value })}
              className="w-full h-9 rounded-lg border border-input bg-background px-3 text-sm"
            >
              <option value="pagi">Pagi</option>
              <option value="siang">Siang</option>
              <option value="sore">Sore</option>
              <option value="malam">Malam</option>
            </select>
          </div>

          <div>
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
              Kategori Penerima
            </label>
            <select
              value={form.kategori}
              onChange={(e) => setForm({ ...form, kategori: e.target.value })}
              className="w-full h-9 rounded-lg border border-input bg-background px-3 text-sm"
            >
              <option value="Siswa">Siswa</option>
              <option value="Ibu Hamil">Ibu Hamil</option>
              <option value="Ibu Menyusui">Ibu Menyusui</option>
            </select>
          </div>

          <div>
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
              Jenis Lokasi MBG
            </label>
            <select
              value={form.lokasi_mbg_tipe}
              onChange={(e) =>
                setForm({
                  ...form,
                  lokasi_mbg_tipe: e.target.value,
                  sekolah_id: "",
                  puskesmas_id: e.target.value === "puskesmas" ? form.puskesmas_id : "",
                  puskesmas_nama:
                    e.target.value === "puskesmas" ? form.puskesmas_nama : "",
                  puskesmas_daerah:
                    e.target.value === "puskesmas" ? form.puskesmas_daerah : "",
                })
              }
              className="w-full h-9 rounded-lg border border-input bg-background px-3 text-sm"
            >
              <option value="sekolah">Sekolah</option>
              <option value="puskesmas">Puskesmas</option>
            </select>
          </div>

          <div className="sm:col-span-2">
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
              Lokasi (opsional)
            </label>
            <Input
              placeholder="Alamat atau GPS koordinat"
              value={form.lokasi}
              onChange={(e) => setForm({ ...form, lokasi: e.target.value })}
              className="rounded-lg"
            />
          </div>
        </div>
      </div>

      {/* 2. Menu Makanan */}
      <div className="bg-card rounded-xl border border-border p-5 sm:p-6 space-y-4">
        <h2 className="font-bold text-foreground flex items-center gap-2">
          <span className="w-6 h-6 bg-primary text-primary-foreground rounded-full text-xs flex items-center justify-center font-black">
            2
          </span>
          Menu Makanan Hari Ini
        </h2>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          {[
            ["menu_nasi", "🍚 Nasi"],
            ["menu_lauk", "🍗 Lauk"],
            ["menu_sayur", "🥦 Sayur"],
            ["menu_buah", "🍎 Buah"],
            ["menu_susu", "🥛 Susu"],
          ].map(([key, label]) => (
            <div key={key}>
              <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
                {label}
              </label>

              <Input
                placeholder={`Contoh: ${label.replace(
                  /[🍚🍗🥦🍎🥛] /,
                  ""
                )}`}
                value={form[key]}
                onChange={(e) =>
                  setForm({ ...form, [key]: e.target.value })
                }
                className="rounded-lg"
              />
            </div>
          ))}
        </div>
      </div>

      {/* 3. Informasi Gizi */}
      <div className="bg-card rounded-xl border border-border p-5 sm:p-6 space-y-4">
        <h2 className="font-bold text-foreground flex items-center gap-2">
          <span className="w-6 h-6 bg-primary text-primary-foreground rounded-full text-xs flex items-center justify-center font-black">
            3
          </span>
          Informasi Gizi Menu
        </h2>

        <p className="text-xs text-muted-foreground">
          Isi perkiraan kandungan gizi per porsi/omprengan. Data ini akan tampil di output menu dan membantu validasi kelayakan gizi.
        </p>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          {[
            ["kalori", "Kalori / Energi (kkal)", "650"],
            ["protein", "Protein (gram)", "25"],
            ["karbohidrat", "Karbohidrat (gram)", "80"],
            ["lemak", "Lemak (gram)", "18"],
            ["serat", "Serat (gram)", "6"],
            ["zat_besi", "Zat Besi (mg)", "4"],
            ["kalsium", "Kalsium (mg)", "250"],
          ].map(([key, label, placeholder]) => (
            <div key={key}>
              <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
                {label}
              </label>
              <Input
                type="number"
                placeholder={`Contoh: ${placeholder}`}
                value={form[key]}
                onChange={(e) => setForm({ ...form, [key]: e.target.value })}
                className="rounded-lg"
              />
            </div>
          ))}

          <div>
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
              Vitamin
            </label>
            <Input
              placeholder="Contoh: A, B, C, D"
              value={form.vitamin}
              onChange={(e) => setForm({ ...form, vitamin: e.target.value })}
              className="rounded-lg"
            />
          </div>

          <div className="sm:col-span-2">
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
              Catatan Gizi
            </label>
            <textarea
              rows={3}
              placeholder="Contoh: Menu tinggi protein dan kalsium, cocok untuk ibu hamil."
              value={form.catatan_gizi}
              onChange={(e) => setForm({ ...form, catatan_gizi: e.target.value })}
              className="w-full rounded-xl border border-input bg-background px-3 py-2 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-ring"
            />
          </div>
        </div>
      </div>

      {/* 4. Bahan Makanan */}
      <div className="bg-card rounded-xl border border-border p-5 sm:p-6 space-y-4">
        <div className="flex items-center justify-between">
          <h2 className="font-bold text-foreground flex items-center gap-2">
            <span className="w-6 h-6 bg-primary text-primary-foreground rounded-full text-xs flex items-center justify-center font-black">
              4
            </span>
            Bahan Makanan
          </h2>

          <Button
            variant="outline"
            size="sm"
            onClick={() => setBahanList([...bahanList, defaultBahan()])}
            className="rounded-full text-xs"
          >
            <Plus className="w-3.5 h-3.5 mr-1" />
            Tambah
          </Button>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border">
                {[
                  "Nama Bahan",
                  "Jumlah",
                  "Satuan",
                  "Harga/Satuan",
                  "Total",
                  "",
                ].map((h) => (
                  <th
                    key={h}
                    className="text-left pb-2 text-xs font-semibold text-muted-foreground pr-2"
                  >
                    {h}
                  </th>
                ))}
              </tr>
            </thead>

            <tbody>
              {bahanList.map((b, i) => (
                <tr key={i} className="border-b border-border/50">
                  <td className="py-2 pr-2">
                    <Input
                      placeholder="Beras"
                      value={b.nama_bahan || b.nama}
                      onChange={(e) =>
                        updateBahan(i, "nama_bahan", e.target.value)
                      }
                      className="rounded-lg h-8 text-xs min-w-24"
                    />
                  </td>

                  <td className="py-2 pr-2">
                    <Input
                      type="number"
                      placeholder="5"
                      value={b.jumlah}
                      onChange={(e) =>
                        updateBahan(i, "jumlah", e.target.value)
                      }
                      className="rounded-lg h-8 text-xs w-16"
                    />
                  </td>

                  <td className="py-2 pr-2">
                    <select
                      value={b.satuan}
                      onChange={(e) =>
                        updateBahan(i, "satuan", e.target.value)
                      }
                      className="h-8 rounded-lg border border-input bg-background px-2 text-xs"
                    >
                      {["kg", "gr", "liter", "ml", "buah", "ikat", "porsi"].map(
                        (s) => (
                          <option key={s} value={s}>
                            {s}
                          </option>
                        )
                      )}
                    </select>
                  </td>

                  <td className="py-2 pr-2">
                    <Input
                      type="number"
                      placeholder="12000"
                      value={b.harga_satuan || b.harga}
                      onChange={(e) =>
                        updateBahan(i, "harga_satuan", e.target.value)
                      }
                      className="rounded-lg h-8 text-xs w-24"
                    />
                  </td>

                  <td className="py-2 pr-2 font-semibold text-primary text-xs whitespace-nowrap">
                    Rp {(b.total || 0).toLocaleString("id-ID")}
                  </td>

                  <td className="py-2">
                    <button
                      type="button"
                      onClick={() =>
                        setBahanList(bahanList.filter((_, j) => j !== i))
                      }
                      className="text-red-400 hover:text-red-600"
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="flex justify-end">
          <div className="bg-primary/5 rounded-lg px-4 py-2 text-sm">
            <span className="text-muted-foreground">Total Bahan: </span>
            <span className="font-black text-primary">
              Rp {totalBahan.toLocaleString("id-ID")}
            </span>
          </div>
        </div>
      </div>

      {/* 5. Data Pengiriman */}
      <div className="bg-card rounded-xl border border-border p-5 sm:p-6 space-y-4">
        <h2 className="font-bold text-foreground flex items-center gap-2">
          <span className="w-6 h-6 bg-primary text-primary-foreground rounded-full text-xs flex items-center justify-center font-black">
            5
          </span>
          Data Pengiriman
        </h2>

        <p className="text-xs text-muted-foreground">
          Pilih lokasi MBG: sekolah penerima atau puskesmas. Jika memilih puskesmas, daerah bisa diisi bebas sesuai lokasi layanan.
        </p>

        {sppgData && (
          <div className="rounded-xl bg-primary/5 border border-primary/10 px-4 py-3 text-sm">
            <span className="text-muted-foreground">SPPG aktif: </span>
            <span className="font-bold text-primary">{sppgData.nama}</span>
            <span className="text-muted-foreground">
              {" "}• {sppgData.kabupaten}, {sppgData.provinsi}
            </span>
          </div>
        )}

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          {form.lokasi_mbg_tipe === "sekolah" ? (
            <div>
              <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
                Lokasi MBG - Pilih Sekolah
              </label>
              <select
                value={form.sekolah_id}
                onChange={(e) =>
                  setForm({ ...form, sekolah_id: e.target.value })
                }
                className="w-full h-9 rounded-lg border border-input bg-background px-3 text-sm"
              >
                <option value="">
                  {loadingSekolah ? "Mengambil data sekolah..." : "Pilih sekolah tujuan"}
                </option>
                {sekolahList.map((item) => (
                  <option key={item.id} value={item.id}>
                    {item.nama_sekolah} - {item.jenjang || "-"} ({item.jumlah_siswa || 0} siswa)
                  </option>
                ))}
              </select>
            </div>
          ) : (
            <>
              <div>
                <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
                  Lokasi MBG - Pilih Puskesmas
                </label>
                <select
                  value={form.puskesmas_id}
                  onChange={(e) => {
                    const selected = puskesmasList.find(
                      (item) => String(item.id) === String(e.target.value)
                    );

                    setForm({
                      ...form,
                      puskesmas_id: e.target.value,
                      puskesmas_nama: selected?.nama_puskesmas || "",
                      puskesmas_daerah: selected
                        ? `${selected.kecamatan || "-"}, ${selected.kabupaten || "-"}`
                        : "",
                    });
                  }}
                  className="w-full h-9 rounded-lg border border-input bg-background px-3 text-sm"
                >
                  <option value="">
                    {puskesmasList.length === 0
                      ? "Belum ada data puskesmas"
                      : "Pilih puskesmas"}
                  </option>

                  {puskesmasList.map((item) => (
                    <option key={item.id} value={item.id}>
                      {item.nama_puskesmas} - {item.kecamatan || "-"}, {item.kabupaten || "-"}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
                  Daerah Puskesmas
                </label>
                <Input
                  placeholder="Contoh: Harau, Lima Puluh Kota"
                  value={form.puskesmas_daerah}
                  onChange={(e) =>
                    setForm({ ...form, puskesmas_daerah: e.target.value })
                  }
                  className="rounded-lg"
                />
              </div>
            </>
          )}

          <div>
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
              Jumlah Omprengan
            </label>
            <Input
              type="number"
              placeholder="Contoh: 35"
              value={form.jumlah_omprengan}
              onChange={(e) =>
                setForm({ ...form, jumlah_omprengan: e.target.value })
              }
              className="rounded-lg"
            />
          </div>

          <div>
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
              Nama Kurir / Sopir
            </label>
            <Input
              placeholder="Contoh: Budi"
              value={form.nama_kurir}
              onChange={(e) =>
                setForm({ ...form, nama_kurir: e.target.value })
              }
              className="rounded-lg"
            />
          </div>

          <div>
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
              Kendaraan
            </label>
            <Input
              placeholder="Contoh: Mobil MBG"
              value={form.kendaraan}
              onChange={(e) =>
                setForm({ ...form, kendaraan: e.target.value })
              }
              className="rounded-lg"
            />
          </div>

          <div>
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
              Plat Nomor
            </label>
            <Input
              placeholder="Contoh: BA 1234 OP"
              value={form.plat_nomor}
              onChange={(e) =>
                setForm({ ...form, plat_nomor: e.target.value })
              }
              className="rounded-lg"
            />
          </div>

          <div>
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
              Jumlah Porsi Otomatis
            </label>
            <Input
              readOnly
              value={
                form.lokasi_mbg_tipe === "sekolah"
                  ? selectedSekolah?.jumlah_siswa || ""
                  : "Diisi lewat jumlah omprengan"
              }
              placeholder={
                form.lokasi_mbg_tipe === "sekolah"
                  ? "Mengikuti jumlah siswa sekolah"
                  : "Untuk puskesmas, gunakan jumlah omprengan"
              }
              className="rounded-lg bg-muted/40"
            />
          </div>
        </div>
      </div>

      {/* 6. Dana */}
      <div className="bg-card rounded-xl border border-border p-5 sm:p-6 space-y-4">
        <h2 className="font-bold text-foreground flex items-center gap-2">
          <span className="w-6 h-6 bg-primary text-primary-foreground rounded-full text-xs flex items-center justify-center font-black">
            6
          </span>
          Dana Digunakan
        </h2>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div>
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
              Total Dana Hari Ini (Rp)
            </label>
            <Input
              type="number"
              placeholder="0"
              value={form.dana_total}
              onChange={(e) =>
                setForm({ ...form, dana_total: e.target.value })
              }
              className="rounded-lg"
            />
          </div>

          <div>
            <label className="text-xs font-semibold text-muted-foreground mb-1.5 block">
              Dana Per Omprengan (Rp)
            </label>
            <Input
              type="number"
              placeholder="0"
              value={form.dana_per_omprengan}
              onChange={(e) =>
                setForm({ ...form, dana_per_omprengan: e.target.value })
              }
              className="rounded-lg"
            />
          </div>
        </div>
      </div>

      {/* 7. Upload Bukti Foto Omprengan */}
      <div className="bg-card rounded-xl border border-border p-5 sm:p-6 space-y-4">
        <h2 className="font-bold text-foreground flex items-center gap-2">
          <span className="w-6 h-6 bg-primary text-primary-foreground rounded-full text-xs flex items-center justify-center font-black">
            7
          </span>
          Upload Bukti Foto Omprengan
        </h2>

        <p className="text-xs text-muted-foreground">
          Foto yang diunggah pada bagian ini akan tersimpan sebagai bukti menu
          omprengan dan makanan jadi dari pihak SPPG.
        </p>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          {[
            {
              label: "📦 Foto Bahan Makanan",
              state: fotoBahan,
              setter: setFotoBahan,
              fileSetter: setFotoBahanFile,
            },
            {
              label: "🍽️ Foto Menu Omprengan / Makanan Jadi",
              state: fotoMakanan,
              setter: setFotoMakanan,
              fileSetter: setFotoMakananFile,
            },
          ].map(({ label, state, setter, fileSetter }) => (
            <label key={label} className="cursor-pointer">
              <p className="text-xs font-semibold text-muted-foreground mb-1.5">
                {label}
              </p>

              <div
                className={`border-2 border-dashed rounded-xl p-6 text-center transition-colors ${
                  state
                    ? "border-emerald-400 bg-emerald-50"
                    : "border-border hover:border-primary/50"
                }`}
              >
                {state ? (
                  <div>
                    <p className="text-xs text-emerald-700 font-semibold">
                      ✓ Foto omprengan terupload
                    </p>
                    <img
                      src={state}
                      alt={label}
                      className="w-32 h-24 rounded-lg object-contain bg-white mx-auto mt-2 border border-emerald-200"
                    />
                  </div>
                ) : (
                  <div>
                    <Upload className="w-6 h-6 text-muted-foreground mx-auto mb-2" />
                    <p className="text-xs text-muted-foreground">
                      Klik untuk upload foto
                    </p>
                  </div>
                )}

                <input
                  type="file"
                  accept="image/jpeg,image/png,image/webp,image/jpg"
                  className="hidden"
                  onChange={(e) => {
                    const file = e.target.files?.[0];
                    if (!file) return;
                    fileSetter(file);
                    handleFileUpload(file, setter);
                  }}
                />
              </div>
            </label>
          ))}
        </div>

        {uploading && (
          <p className="text-xs text-primary text-center">
            Mengupload foto omprengan ke server...
          </p>
        )}
      </div>

      {/* 8. Catatan */}
      <div className="bg-card rounded-xl border border-border p-5 sm:p-6 space-y-4">
        <h2 className="font-bold text-foreground flex items-center gap-2">
          <span className="w-6 h-6 bg-primary text-primary-foreground rounded-full text-xs flex items-center justify-center font-black">
            8
          </span>
          Catatan Tambahan
        </h2>

        <textarea
          rows={3}
          placeholder="Keterangan tambahan (opsional)..."
          value={form.catatan}
          onChange={(e) => setForm({ ...form, catatan: e.target.value })}
          className="w-full rounded-xl border border-input bg-background px-3 py-2 text-sm resize-none focus:outline-none focus:ring-2 focus:ring-ring"
        />
      </div>

      {/* Submit */}
      <div className="flex gap-3 justify-end">
        <Button
          variant="outline"
          onClick={() => handleSubmit("draft")}
          disabled={submitting}
          className="rounded-full"
        >
          <Save className="w-4 h-4 mr-1" />
          Simpan Draft
        </Button>

        <Button
          onClick={() => handleSubmit("menunggu_validasi")}
          disabled={submitting || uploading}
          className="rounded-full bg-primary"
        >
          <Send className="w-4 h-4 mr-1" />
          {submitting ? "Mengirim..." : "Kirim untuk Validasi"}
        </Button>
      </div>
    </div>
  );
}