import { useState } from "react";
import { ShieldCheck, Upload, X } from "lucide-react";

const VALIDASI_API = "http://openplate.my.id/api/tracking/validasi-sekolah.php";

export default function ValidasiSekolahForm({ pengirimanId, jumlahPorsi = 0, onValidated }) {
  const [open, setOpen] = useState(false);
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState({
    validasi_menu: "sesuai",
    validasi_jumlah: "sesuai",
    validasi_kondisi: "baik",
    jumlah_diterima: jumlahPorsi || "",
    catatan_validasi: "",
    foto_penerimaan: null,
  });

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

    if (name === "foto_penerimaan") {
      setForm((prev) => ({ ...prev, foto_penerimaan: files?.[0] || null }));
      return;
    }

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

  const reset = () => {
    setForm({
      validasi_menu: "sesuai",
      validasi_jumlah: "sesuai",
      validasi_kondisi: "baik",
      jumlah_diterima: jumlahPorsi || "",
      catatan_validasi: "",
      foto_penerimaan: null,
    });
  };

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

    if (!pengirimanId) {
      alert("ID pengiriman tidak valid.");
      return;
    }

    if (!form.foto_penerimaan) {
      alert("Foto penerimaan wajib diupload.");
      return;
    }

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

    try {
      setSaving(true);

      const formData = new FormData();
      formData.append("id", pengirimanId);
      formData.append("validasi_menu", form.validasi_menu);
      formData.append("validasi_jumlah", form.validasi_jumlah);
      formData.append("validasi_kondisi", form.validasi_kondisi);
      formData.append("jumlah_diterima", form.jumlah_diterima);
      formData.append("catatan_validasi", form.catatan_validasi);
      formData.append("foto_penerimaan", form.foto_penerimaan);

      const res = await fetch(VALIDASI_API, {
        method: "POST",
        body: formData,
      });

      const result = await res.json();

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

      alert(
        result.data?.status === "selesai"
          ? "Validasi berhasil. Pengiriman selesai."
          : "Validasi tersimpan. Pengiriman ditandai bermasalah."
      );

      reset();
      setOpen(false);

      if (typeof onValidated === "function") {
        onValidated();
      }
    } catch (err) {
      console.error("Gagal validasi:", err);
      alert("Tidak bisa terhubung ke server.");
    } finally {
      setSaving(false);
    }
  };

  if (!open) {
    return (
      <button
        type="button"
        onClick={() => setOpen(true)}
        className="rounded-xl bg-emerald-50 px-4 py-2 text-sm font-bold text-emerald-700 hover:bg-emerald-100"
      >
        <ShieldCheck className="mr-1 inline h-4 w-4" />
        Validasi Sekolah
      </button>
    );
  }

  return (
    <div className="mt-4 rounded-2xl border border-emerald-200 bg-emerald-50 p-4">
      <div className="mb-3 flex items-start justify-between gap-3">
        <div>
          <h4 className="font-black text-emerald-900">Validasi Pihak Sekolah</h4>
          <p className="mt-1 text-sm text-emerald-700">
            Cek kesesuaian menu, jumlah, kondisi makanan, lalu upload foto penerimaan.
          </p>
        </div>

        <button
          type="button"
          onClick={() => {
            reset();
            setOpen(false);
          }}
          className="rounded-lg bg-white p-2 text-emerald-700 hover:bg-emerald-100"
        >
          <X className="h-4 w-4" />
        </button>
      </div>

      <form onSubmit={handleSubmit} className="grid grid-cols-1 gap-3 lg:grid-cols-3">
        <div>
          <label className="mb-1 block text-xs font-bold text-emerald-900">
            Validasi Menu
          </label>
          <select
            name="validasi_menu"
            value={form.validasi_menu}
            onChange={handleChange}
            className="w-full rounded-xl border border-emerald-200 bg-white px-3 py-2 text-sm"
          >
            <option value="sesuai">Sesuai</option>
            <option value="tidak_sesuai">Tidak Sesuai</option>
          </select>
        </div>

        <div>
          <label className="mb-1 block text-xs font-bold text-emerald-900">
            Validasi Jumlah
          </label>
          <select
            name="validasi_jumlah"
            value={form.validasi_jumlah}
            onChange={handleChange}
            className="w-full rounded-xl border border-emerald-200 bg-white px-3 py-2 text-sm"
          >
            <option value="sesuai">Sesuai</option>
            <option value="tidak_sesuai">Tidak Sesuai</option>
          </select>
        </div>

        <div>
          <label className="mb-1 block text-xs font-bold text-emerald-900">
            Kondisi Makanan
          </label>
          <select
            name="validasi_kondisi"
            value={form.validasi_kondisi}
            onChange={handleChange}
            className="w-full rounded-xl border border-emerald-200 bg-white px-3 py-2 text-sm"
          >
            <option value="baik">Baik</option>
            <option value="kurang_baik">Kurang Baik</option>
            <option value="bermasalah">Bermasalah</option>
          </select>
        </div>

        <div>
          <label className="mb-1 block text-xs font-bold text-emerald-900">
            Jumlah Diterima
          </label>
          <input
            type="number"
            name="jumlah_diterima"
            value={form.jumlah_diterima}
            onChange={handleChange}
            className="w-full rounded-xl border border-emerald-200 bg-white px-3 py-2 text-sm"
          />
        </div>

        <div>
          <label className="mb-1 block text-xs font-bold text-emerald-900">
            Foto Penerimaan
          </label>
          <input
            type="file"
            name="foto_penerimaan"
            accept="image/*"
            onChange={handleChange}
            className="w-full rounded-xl border border-emerald-200 bg-white px-3 py-2 text-sm"
          />
        </div>

        <div>
          <label className="mb-1 block text-xs font-bold text-emerald-900">
            Catatan
          </label>
          <input
            name="catatan_validasi"
            value={form.catatan_validasi}
            onChange={handleChange}
            placeholder="Catatan jika ada"
            className="w-full rounded-xl border border-emerald-200 bg-white px-3 py-2 text-sm"
          />
        </div>

        <button
          type="submit"
          disabled={saving}
          className="inline-flex items-center justify-center gap-2 rounded-xl bg-emerald-700 px-4 py-2 text-sm font-bold text-white hover:bg-emerald-800 disabled:opacity-60 lg:col-span-3"
        >
          <Upload className="h-4 w-4" />
          {saving ? "Menyimpan..." : "Simpan Validasi"}
        </button>
      </form>
    </div>
  );
}
