import { useState } from "react";
import CreatePengirimanForm from "../../components/CreatePengirimanForm";
import MonitoringPengiriman from "../../components/MonitoringPengiriman";

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

export default function SPPGPengiriman() {
  const [sppgId, setSppgId] = useState(getSppgId());
  const [manualSppgId, setManualSppgId] = useState(getSppgId());

  const saveManualSppgId = () => {
    const cleanId = String(manualSppgId || "").trim();

    if (!cleanId) {
      alert("ID SPPG wajib diisi.");
      return;
    }

    localStorage.setItem("sppg_id", cleanId);
    setSppgId(cleanId);
  };

  return (
    <div className="p-4 sm:p-6 lg:p-8 max-w-7xl mx-auto">
      {!sppgId && (
        <div className="mb-5 rounded-3xl border border-amber-200 bg-amber-50 p-5">
          <h2 className="text-lg font-black text-amber-900">
            ID SPPG belum ditemukan
          </h2>

          <p className="mt-1 text-sm font-semibold text-amber-700">
            Form tambah pengiriman belum muncul karena sistem belum tahu akun ini milik SPPG ID berapa.
            Masukkan ID SPPG yang sesuai dengan tabel <b>sppg</b> di database.
          </p>

          <div className="mt-4 flex flex-col gap-3 sm:flex-row">
            <input
              value={manualSppgId}
              onChange={(e) => setManualSppgId(e.target.value)}
              placeholder="Contoh: 1"
              className="w-full rounded-xl border border-amber-200 bg-white px-4 py-3 text-sm outline-none sm:max-w-xs"
            />

            <button
              type="button"
              onClick={saveManualSppgId}
              className="rounded-xl bg-amber-600 px-5 py-3 text-sm font-bold text-white hover:bg-amber-700"
            >
              Simpan ID SPPG
            </button>
          </div>
        </div>
      )}

      {sppgId && <CreatePengirimanForm sppgId={sppgId} />}

      <MonitoringPengiriman role="sppg" sppgId={sppgId} />
    </div>
  );
}
