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

const UPDATE_API = "http://localhost/backend/api/tracking/update-status.php";

const statusOptions = [
  { value: "persiapan", label: "Persiapan Dapur" },
  { value: "packing", label: "Packing" },
  { value: "berangkat", label: "Omprengan Berangkat" },
  { value: "dalam_perjalanan", label: "Dalam Perjalanan" },
  { value: "tiba_di_sekolah", label: "Tiba di Sekolah" },
  { value: "diterima_sekolah", label: "Diterima Pihak Sekolah" },
  { value: "selesai", label: "Distribusi Selesai" },
  { value: "bermasalah", label: "Bermasalah" },
];

export default function StatusOverrideAdmin({ pengirimanId, currentStatus, onUpdated }) {
  const [open, setOpen] = useState(false);
  const [status, setStatus] = useState(currentStatus || "persiapan");
  const [catatan, setCatatan] = useState("");
  const [saving, setSaving] = useState(false);

  const handleSave = async () => {
    if (!pengirimanId) {
      alert("ID pengiriman tidak valid.");
      return;
    }

    try {
      setSaving(true);

      const res = await fetch(UPDATE_API, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          id: pengirimanId,
          status,
          catatan_sppg: catatan || "Status diubah manual oleh admin.",
        }),
      });

      const result = await res.json();

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

      alert("Status berhasil diubah.");
      setOpen(false);
      setCatatan("");

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

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

  return (
    <div className="mt-4 w-full rounded-2xl border border-slate-200 bg-slate-50 p-4">
      <div className="mb-3 flex items-start justify-between gap-3">
        <div>
          <h4 className="font-black text-slate-900">Ubah Status Manual Admin</h4>
          <p className="mt-1 text-sm text-slate-500">
            Dipakai kalau admin salah menandai bermasalah atau perlu memperbaiki status pengiriman.
          </p>
        </div>

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

      <div className="grid grid-cols-1 gap-3 lg:grid-cols-[220px_1fr_auto]">
        <select
          value={status}
          onChange={(e) => setStatus(e.target.value)}
          className="rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm font-semibold outline-none"
        >
          {statusOptions.map((item) => (
            <option key={item.value} value={item.value}>
              {item.label}
            </option>
          ))}
        </select>

        <input
          value={catatan}
          onChange={(e) => setCatatan(e.target.value)}
          placeholder="Catatan admin, contoh: salah tandai bermasalah, dikembalikan ke dalam perjalanan"
          className="rounded-xl border border-slate-200 bg-white px-3 py-2 text-sm outline-none"
        />

        <button
          type="button"
          onClick={handleSave}
          disabled={saving}
          className="inline-flex items-center justify-center gap-2 rounded-xl bg-blue-700 px-4 py-2 text-sm font-bold text-white hover:bg-blue-800 disabled:opacity-60"
        >
          <Save className="h-4 w-4" />
          {saving ? "Menyimpan..." : "Simpan"}
        </button>
      </div>
    </div>
  );
}
