import { useEffect, useState } from "react";
import { Plus, Truck, X, Save } from "lucide-react";

const CREATE_API = "http://openplate.my.id/api/tracking/create.php";
const SEKOLAH_API = "http://openplate.my.id/api/sekolah/list.php";

export default function CreatePengirimanForm({ sppgId = "", onCreated }) {
  const [open, setOpen] = useState(false);
  const [sekolahList, setSekolahList] = useState([]);
  const [saving, setSaving] = useState(false);
  const [loadingSekolah, setLoadingSekolah] = useState(false);

  const [form, setForm] = useState({
    sekolah_id: "",
    nama_sekolah: "",
    tujuan_alamat: "",
    jumlah_porsi: "",
    jumlah_omprengan: "",
    nama_kurir: "",
    kendaraan: "",
    plat_nomor: "",
    catatan_sppg: "",
  });

  const loadSekolah = async () => {
    if (!sppgId) return;

    try {
      setLoadingSekolah(true);

      const res = await fetch(`${SEKOLAH_API}?sppg_id=${sppgId}`);
      const result = await res.json();

      if (result.success && Array.isArray(result.data)) {
        setSekolahList(result.data);
      } else {
        setSekolahList([]);
      }
    } catch (err) {
      console.error("Gagal mengambil sekolah:", err);
      setSekolahList([]);
    } finally {
      setLoadingSekolah(false);
    }
  };

  useEffect(() => {
    if (open) {
      loadSekolah();
    }
  }, [open, sppgId]);

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

    if (name === "sekolah_id") {
      const selected = sekolahList.find((item) => String(item.id) === String(value));

      setForm((prev) => ({
        ...prev,
        sekolah_id: value,
        nama_sekolah: selected?.nama_sekolah || "",
        tujuan_alamat: selected?.alamat || prev.tujuan_alamat || "",
        jumlah_porsi: selected?.jumlah_siswa || prev.jumlah_porsi || "",
      }));

      return;
    }

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

  const resetForm = () => {
    setForm({
      sekolah_id: "",
      nama_sekolah: "",
      tujuan_alamat: "",
      jumlah_porsi: "",
      jumlah_omprengan: "",
      nama_kurir: "",
      kendaraan: "",
      plat_nomor: "",
      catatan_sppg: "",
    });
  };

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

    if (!sppgId) {
      alert("ID SPPG belum ditemukan. Pastikan akun SPPG punya sppg_id di localStorage.");
      return;
    }

    if (!form.nama_sekolah.trim()) {
      alert("Nama sekolah wajib diisi.");
      return;
    }

    if (Number(form.jumlah_porsi) <= 0) {
      alert("Jumlah porsi wajib lebih dari 0.");
      return;
    }

    try {
      setSaving(true);

      const res = await fetch(CREATE_API, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          sppg_id: Number(sppgId),
          sekolah_id: form.sekolah_id ? Number(form.sekolah_id) : null,
          nama_sekolah: form.nama_sekolah,
          tujuan_alamat: form.tujuan_alamat,
          jumlah_porsi: Number(form.jumlah_porsi) || 0,
          jumlah_omprengan: Number(form.jumlah_omprengan) || 0,
          nama_kurir: form.nama_kurir,
          kendaraan: form.kendaraan,
          plat_nomor: form.plat_nomor,
          catatan_sppg: form.catatan_sppg,
        }),
      });

      const result = await res.json();

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

      alert(`Pengiriman berhasil dibuat. Kode konfirmasi: ${result.data?.kode_konfirmasi || "-"}`);

      resetForm();
      setOpen(false);

      if (typeof onCreated === "function") {
        onCreated();
      }

      window.dispatchEvent(new Event("tracking-pengiriman-created"));
    } catch (err) {
      console.error("Gagal membuat pengiriman:", err);
      alert("Tidak bisa terhubung ke server.");
    } finally {
      setSaving(false);
    }
  };

  if (!open) {
    return (
      <div className="mb-6 rounded-3xl border border-blue-200 bg-blue-50 p-5 shadow-sm">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
          <div>
            <div className="inline-flex items-center gap-2 rounded-full bg-white px-3 py-1 text-xs font-bold text-blue-700">
              <Truck className="h-4 w-4" />
              Buat Pengiriman Baru
            </div>
            <h2 className="mt-3 text-xl font-black text-slate-950">
              Mulai Distribusi MBG
            </h2>
            <p className="mt-1 text-sm text-slate-600">
              Buat pengiriman baru ke sekolah tujuan. Status awal otomatis menjadi Persiapan Dapur.
            </p>
          </div>

          <button
            type="button"
            onClick={() => setOpen(true)}
            className="inline-flex w-fit items-center gap-2 rounded-xl bg-blue-700 px-4 py-3 text-sm font-bold text-white shadow-sm hover:bg-blue-800"
          >
            <Plus className="h-4 w-4" />
            Tambah Pengiriman
          </button>
        </div>
      </div>
    );
  }

  return (
    <form
      onSubmit={handleSubmit}
      className="mb-6 rounded-3xl border border-blue-200 bg-white p-5 shadow-sm"
    >
      <div className="mb-5 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <h2 className="text-xl font-black text-slate-950">
            Form Pengiriman Baru
          </h2>
          <p className="mt-1 text-sm text-slate-500">
            Isi data pengiriman sesuai kondisi nyata di dapur SPPG.
          </p>
        </div>

        <button
          type="button"
          onClick={() => {
            resetForm();
            setOpen(false);
          }}
          className="inline-flex w-fit items-center gap-2 rounded-xl border border-slate-200 px-3 py-2 text-sm font-bold text-slate-600 hover:bg-slate-50"
        >
          <X className="h-4 w-4" />
          Tutup
        </button>
      </div>

      <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
        <div>
          <label className="mb-1 block text-sm font-bold text-slate-700">
            Sekolah Tujuan
          </label>
          <select
            name="sekolah_id"
            value={form.sekolah_id}
            onChange={handleChange}
            className="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm outline-none"
          >
            <option value="">
              {loadingSekolah ? "Mengambil sekolah..." : "Pilih sekolah / isi manual"}
            </option>
            {sekolahList.map((item) => (
              <option key={item.id} value={item.id}>
                {item.nama_sekolah} - {item.jenjang || "-"}
              </option>
            ))}
          </select>
        </div>

        <div>
          <label className="mb-1 block text-sm font-bold text-slate-700">
            Nama Sekolah
          </label>
          <input
            name="nama_sekolah"
            value={form.nama_sekolah}
            onChange={handleChange}
            placeholder="Contoh: SDN 05 Payakumbuh"
            className="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm outline-none"
            required
          />
        </div>

        <div>
          <label className="mb-1 block text-sm font-bold text-slate-700">
            Alamat Tujuan
          </label>
          <input
            name="tujuan_alamat"
            value={form.tujuan_alamat}
            onChange={handleChange}
            placeholder="Alamat sekolah tujuan"
            className="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm outline-none"
          />
        </div>

        <div>
          <label className="mb-1 block text-sm font-bold text-slate-700">
            Jumlah Porsi
          </label>
          <input
            type="number"
            name="jumlah_porsi"
            value={form.jumlah_porsi}
            onChange={handleChange}
            placeholder="Contoh: 350"
            className="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm outline-none"
            required
          />
        </div>

        <div>
          <label className="mb-1 block text-sm font-bold text-slate-700">
            Jumlah Omprengan
          </label>
          <input
            type="number"
            name="jumlah_omprengan"
            value={form.jumlah_omprengan}
            onChange={handleChange}
            placeholder="Contoh: 35"
            className="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm outline-none"
          />
        </div>

        <div>
          <label className="mb-1 block text-sm font-bold text-slate-700">
            Nama Kurir / Sopir
          </label>
          <input
            name="nama_kurir"
            value={form.nama_kurir}
            onChange={handleChange}
            placeholder="Nama petugas pengantar"
            className="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm outline-none"
          />
        </div>

        <div>
          <label className="mb-1 block text-sm font-bold text-slate-700">
            Kendaraan
          </label>
          <input
            name="kendaraan"
            value={form.kendaraan}
            onChange={handleChange}
            placeholder="Contoh: Mobil MBG / Motor"
            className="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm outline-none"
          />
        </div>

        <div>
          <label className="mb-1 block text-sm font-bold text-slate-700">
            Plat Nomor
          </label>
          <input
            name="plat_nomor"
            value={form.plat_nomor}
            onChange={handleChange}
            placeholder="Contoh: BA 1234 XX"
            className="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm outline-none"
          />
        </div>

        <div>
          <label className="mb-1 block text-sm font-bold text-slate-700">
            Catatan SPPG
          </label>
          <input
            name="catatan_sppg"
            value={form.catatan_sppg}
            onChange={handleChange}
            placeholder="Catatan tambahan"
            className="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm outline-none"
          />
        </div>
      </div>

      <div className="mt-5 flex flex-wrap gap-3">
        <button
          type="submit"
          disabled={saving}
          className="inline-flex items-center gap-2 rounded-xl bg-blue-700 px-5 py-3 text-sm font-bold text-white hover:bg-blue-800 disabled:opacity-60"
        >
          <Save className="h-4 w-4" />
          {saving ? "Menyimpan..." : "Buat Pengiriman"}
        </button>

        <button
          type="button"
          onClick={resetForm}
          className="rounded-xl border border-slate-200 px-5 py-3 text-sm font-bold text-slate-600 hover:bg-slate-50"
        >
          Reset
        </button>
      </div>
    </form>
  );
}
