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

const UPLOAD_API = "http://openplate.my.id/api/tracking/upload-bukti-sppg.php";

export default function UploadBuktiSPPG({ pengirimanId, onUploaded }) {
  const [open, setOpen] = useState(false);
  const [fotoOmprengan, setFotoOmprengan] = useState(null);
  const [fotoMenu, setFotoMenu] = useState(null);
  const [saving, setSaving] = useState(false);

  const reset = () => {
    setFotoOmprengan(null);
    setFotoMenu(null);
  };

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

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

    if (!fotoOmprengan && !fotoMenu) {
      alert("Minimal upload foto omprengan atau foto menu.");
      return;
    }

    try {
      setSaving(true);

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

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

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

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

      const result = await res.json();

      if (!result.success) {
        alert(result.message || "Gagal upload bukti SPPG.");
        return;
      }

      alert("Bukti SPPG berhasil diupload.");
      reset();
      setOpen(false);

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

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

  return (
    <div className="mt-4 rounded-2xl border border-amber-200 bg-amber-50 p-4">
      <div className="mb-3 flex items-start justify-between gap-3">
        <div>
          <h4 className="font-black text-amber-900">Upload Bukti SPPG</h4>
          <p className="mt-1 text-sm text-amber-700">
            Upload foto omprengan dan menu makanan hari ini sebagai bukti pengiriman.
          </p>
        </div>

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

      <form onSubmit={handleSubmit} className="grid grid-cols-1 gap-3 md:grid-cols-[1fr_1fr_auto]">
        <div>
          <label className="mb-1 block text-xs font-bold text-amber-900">
            Foto Omprengan
          </label>
          <input
            type="file"
            accept="image/*"
            onChange={(e) => setFotoOmprengan(e.target.files?.[0] || null)}
            className="w-full rounded-xl border border-amber-200 bg-white px-3 py-2 text-sm"
          />
        </div>

        <div>
          <label className="mb-1 block text-xs font-bold text-amber-900">
            Foto Menu Hari Ini
          </label>
          <input
            type="file"
            accept="image/*"
            onChange={(e) => setFotoMenu(e.target.files?.[0] || null)}
            className="w-full rounded-xl border border-amber-200 bg-white px-3 py-2 text-sm"
          />
        </div>

        <button
          type="submit"
          disabled={saving}
          className="mt-5 inline-flex items-center justify-center gap-2 rounded-xl bg-amber-600 px-4 py-2 text-sm font-bold text-white hover:bg-amber-700 disabled:opacity-60 md:mt-auto"
        >
          <Upload className="h-4 w-4" />
          {saving ? "Upload..." : "Simpan"}
        </button>
      </form>
    </div>
  );
}
