import { useEffect, useMemo, useState } from "react";
import {
  Truck,
  Search,
  RefreshCw,
  MapPin,
  Utensils,
  PackageCheck,
  AlertTriangle,
  CheckCircle2,
  Clock,
  ShieldCheck,
  Image as ImageIcon,
} from "lucide-react";

import UploadBuktiSPPG from "./UploadBuktiSPPG";
import ValidasiSekolahForm from "./ValidasiSekolahForm";
import RekapPengiriman from "./RekapPengiriman";
import StatusOverrideAdmin from "./StatusOverrideAdmin";

const LIST_API = "http://openplate.my.id/api/tracking/list.php";
const OPTIONS_API = "http://openplate.my.id/api/tracking/options.php";

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

const statusSteps = [
  "persiapan",
  "packing",
  "berangkat",
  "dalam_perjalanan",
  "tiba_di_sekolah",
  "diterima_sekolah",
  "selesai",
];

const statusColors = {
  persiapan: "bg-blue-100 text-blue-700",
  packing: "bg-indigo-100 text-indigo-700",
  berangkat: "bg-amber-100 text-amber-700",
  dalam_perjalanan: "bg-cyan-100 text-cyan-700",
  tiba_di_sekolah: "bg-purple-100 text-purple-700",
  diterima_sekolah: "bg-emerald-100 text-emerald-700",
  selesai: "bg-green-100 text-green-700",
  bermasalah: "bg-red-100 text-red-700",
};

const formatDateTime = (value) => {
  if (!value) return "-";

  return new Date(value).toLocaleString("id-ID", {
    day: "2-digit",
    month: "short",
    hour: "2-digit",
    minute: "2-digit",
  });
};

const fileUrl = (path) => {
  if (!path) return "";
  if (String(path).startsWith("http")) return path;

  return `http://localhost/backend/${path}`;
};

export default function MonitoringPengiriman({
  role = "admin",
  sppgId = "",
  sekolahId = "",
}) {
  const [items, setItems] = useState([]);
  const [summary, setSummary] = useState({
    total_pengiriman: 0,
    berjalan: 0,
    selesai: 0,
    bermasalah: 0,
    total_porsi: 0,
  });

  const [tanggal, setTanggal] = useState(() =>
    new Date().toISOString().slice(0, 10)
  );

  const [status, setStatus] = useState("semua");
  const [search, setSearch] = useState("");
  const [provinsi, setProvinsi] = useState("");
  const [kabupaten, setKabupaten] = useState("");
  const [selectedSppgId, setSelectedSppgId] = useState("");

  const [wilayahOptions, setWilayahOptions] = useState({
    provinsi: [],
    kabupaten: [],
    sppg: [],
  });

  const [loading, setLoading] = useState(true);
  const [savingId, setSavingId] = useState(null);
  const [error, setError] = useState("");

  const canMonitorAll = role === "admin" || role === "pemerintah";
  const canUpdateStatus = role === "admin" || role === "sppg";
  const canUploadBukti = role === "admin" || role === "sppg";
  const canValidate = role === "validator" || role === "sekolah" || role === "admin";
  const canSeeRekap = role === "admin" || role === "pemerintah" || role === "sppg";
  const canShowActions = role !== "pemerintah";

  const isPemerintah = role === "pemerintah";

  const loadWilayahOptions = async () => {
    try {
      const params = new URLSearchParams();

      if (provinsi) params.set("provinsi", provinsi);
      if (kabupaten) params.set("kabupaten", kabupaten);

      const res = await fetch(`${OPTIONS_API}?${params.toString()}`);
      const result = await res.json();

      if (result.success) {
        setWilayahOptions({
          provinsi: Array.isArray(result.data?.provinsi)
            ? result.data.provinsi
            : [],
          kabupaten: Array.isArray(result.data?.kabupaten)
            ? result.data.kabupaten
            : [],
          sppg: Array.isArray(result.data?.sppg) ? result.data.sppg : [],
        });
      }
    } catch (err) {
      console.error("Gagal mengambil opsi wilayah:", err);
    }
  };

  const loadData = async (showSpinner = true) => {
    try {
      if (showSpinner) setLoading(true);
      setError("");

      const params = new URLSearchParams({
        role,
        tanggal,
        status,
      });

      if (sppgId) params.set("sppg_id", String(sppgId));
      if (!sppgId && selectedSppgId) {
        params.set("sppg_id", String(selectedSppgId));
      }
      if (sekolahId) params.set("sekolah_id", String(sekolahId));
      if (provinsi) params.set("provinsi", provinsi);
      if (kabupaten) params.set("kabupaten", kabupaten);

      const res = await fetch(`${LIST_API}?${params.toString()}`);

      if (!res.ok) throw new Error(`HTTP Error ${res.status}`);

      const result = await res.json();

      if (!result.success) {
        setError(result.message || "Gagal mengambil data pengiriman");
        setItems([]);
        return;
      }

      setSummary(
        result.data?.summary || {
          total_pengiriman: 0,
          berjalan: 0,
          selesai: 0,
          bermasalah: 0,
          total_porsi: 0,
        }
      );

      setItems(Array.isArray(result.data?.items) ? result.data.items : []);
    } catch (err) {
      console.error("Gagal mengambil monitoring pengiriman:", err);
      setError("Gagal mengambil data monitoring pengiriman dari server.");
      setItems([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadWilayahOptions();
  }, [provinsi, kabupaten]);

  useEffect(() => {
    loadData();

    const interval = setInterval(() => loadData(false), 5000);
    return () => clearInterval(interval);
  }, [
    role,
    sppgId,
    sekolahId,
    tanggal,
    status,
    provinsi,
    kabupaten,
    selectedSppgId,
  ]);

  const filteredItems = useMemo(() => {
    const keyword = search.trim().toLowerCase();

    if (!keyword) return items;

    return items.filter((item) => {
      const combined = [
        item.nama_sppg,
        item.nama_sekolah,
        item.kabupaten,
        item.provinsi,
        item.nama_kurir,
        item.kendaraan,
        item.plat_nomor,
        item.status,
        item.kode_konfirmasi,
      ]
        .join(" ")
        .toLowerCase();

      return combined.includes(keyword);
    });
  }, [items, search]);

  const updateStatus = async (id, nextStatus) => {
    if (!canUpdateStatus) {
      alert("Akses ditolak. Role ini hanya dapat memantau pengiriman.");
      return;
    }

    try {
      setSavingId(id);

      const res = await fetch(
        "http://localhost/backend/api/tracking/update-status.php",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            id,
            status: nextStatus,
            catatan_sppg: "",
          }),
        }
      );

      const result = await res.json();

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

      await loadData(false);
    } catch (err) {
      console.error("Gagal update status:", err);
      alert("Tidak bisa terhubung ke server");
    } finally {
      setSavingId(null);
    }
  };

  const getNextStatus = (current) => {
    const index = statusSteps.indexOf(current);
    if (index < 0 || index >= statusSteps.length - 1) return null;
    return statusSteps[index + 1];
  };

  return (
    <section className="space-y-6">
      {canSeeRekap && <RekapPengiriman role={role} sppgId={sppgId} />}

      {isPemerintah && (
        <div className="rounded-3xl border border-blue-100 bg-blue-50 p-5 text-sm text-blue-800">
          <div className="flex items-start gap-3">
            <ShieldCheck className="mt-0.5 h-5 w-5 flex-shrink-0" />

            <div>
              <p className="font-black">Mode Monitoring Pemerintah</p>
              <p className="mt-1 leading-relaxed">
                Pemerintah hanya dapat memantau status pengiriman, bukti,
                validasi, wilayah, jumlah porsi, dan progres distribusi. Fitur
                update status, upload bukti, override, dan validasi tidak
                tersedia untuk role pemerintah.
              </p>
            </div>
          </div>
        </div>
      )}

      <div className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
        <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
          <div>
            <div className="inline-flex items-center gap-2 rounded-full bg-blue-50 px-3 py-1 text-xs font-bold text-blue-700">
              <Truck className="h-4 w-4" />
              Monitoring Pengiriman MBG
            </div>

            <h1 className="mt-3 text-2xl font-black text-slate-950">
              Monitoring Pengiriman
            </h1>

            <p className="mt-1 text-sm text-slate-500">
              SPPG mengirim bukti, pihak sekolah memvalidasi, admin dan
              pemerintah memantau seluruh proses pengiriman.
            </p>
          </div>

          <button
            type="button"
            onClick={() => loadData(true)}
            className="inline-flex w-fit items-center gap-2 rounded-xl border border-slate-200 px-4 py-2 text-sm font-bold text-slate-700 hover:bg-slate-50"
          >
            <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
            Refresh
          </button>
        </div>

        <div className="mt-6 grid grid-cols-2 gap-4 lg:grid-cols-5">
          <div className="rounded-2xl bg-blue-50 p-4">
            <p className="text-sm font-semibold text-blue-700">Total</p>
            <p className="mt-1 text-2xl font-black text-blue-700">
              {summary.total_pengiriman}
            </p>
          </div>

          <div className="rounded-2xl bg-cyan-50 p-4">
            <p className="text-sm font-semibold text-cyan-700">Berjalan</p>
            <p className="mt-1 text-2xl font-black text-cyan-700">
              {summary.berjalan}
            </p>
          </div>

          <div className="rounded-2xl bg-green-50 p-4">
            <p className="text-sm font-semibold text-green-700">Selesai</p>
            <p className="mt-1 text-2xl font-black text-green-700">
              {summary.selesai}
            </p>
          </div>

          <div className="rounded-2xl bg-red-50 p-4">
            <p className="text-sm font-semibold text-red-700">Bermasalah</p>
            <p className="mt-1 text-2xl font-black text-red-700">
              {summary.bermasalah}
            </p>
          </div>

          <div className="rounded-2xl bg-amber-50 p-4">
            <p className="text-sm font-semibold text-amber-700">Total Porsi</p>
            <p className="mt-1 text-2xl font-black text-amber-700">
              {Number(summary.total_porsi || 0).toLocaleString("id-ID")}
            </p>
          </div>
        </div>
      </div>

      <div className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
        <div className="grid grid-cols-1 gap-3 lg:grid-cols-6">
          <input
            type="date"
            value={tanggal}
            onChange={(e) => setTanggal(e.target.value)}
            className="rounded-xl border border-slate-200 px-3 py-2 text-sm outline-none"
          />

          <select
            value={provinsi}
            onChange={(e) => {
              setProvinsi(e.target.value);
              setKabupaten("");
              setSelectedSppgId("");
            }}
            className="rounded-xl border border-slate-200 px-3 py-2 text-sm outline-none"
          >
            <option value="">Semua Provinsi</option>
            {wilayahOptions.provinsi.map((item) => (
              <option key={item} value={item}>
                {item}
              </option>
            ))}
          </select>

          <select
            value={kabupaten}
            onChange={(e) => {
              setKabupaten(e.target.value);
              setSelectedSppgId("");
            }}
            className="rounded-xl border border-slate-200 px-3 py-2 text-sm outline-none"
          >
            <option value="">Semua Kabupaten/Kota</option>
            {wilayahOptions.kabupaten.map((item) => (
              <option key={item} value={item}>
                {item}
              </option>
            ))}
          </select>

          <select
            value={selectedSppgId}
            onChange={(e) => setSelectedSppgId(e.target.value)}
            disabled={Boolean(sppgId)}
            className="rounded-xl border border-slate-200 px-3 py-2 text-sm outline-none disabled:bg-slate-100"
          >
            <option value="">{sppgId ? "SPPG Login" : "Semua SPPG"}</option>
            {wilayahOptions.sppg.map((item) => (
              <option key={item.id} value={item.id}>
                {item.nama}
              </option>
            ))}
          </select>

          <select
            value={status}
            onChange={(e) => setStatus(e.target.value)}
            className="rounded-xl border border-slate-200 px-3 py-2 text-sm outline-none"
          >
            <option value="semua">Semua Status</option>
            {Object.entries(statusLabels).map(([key, label]) => (
              <option key={key} value={key}>
                {label}
              </option>
            ))}
          </select>

          <div className="relative">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
            <input
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              placeholder="Cari sekolah, kurir, kendaraan..."
              className="w-full rounded-xl border border-slate-200 py-2 pl-10 pr-3 text-sm outline-none"
            />
          </div>
        </div>
      </div>

      {error && (
        <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm font-semibold text-red-600">
          {error}
        </div>
      )}

      <div className="space-y-4">
        {loading ? (
          <div className="rounded-3xl border border-slate-200 bg-white p-10 text-center text-sm text-slate-500">
            Mengambil data pengiriman...
          </div>
        ) : filteredItems.length === 0 ? (
          <div className="rounded-3xl border border-slate-200 bg-white p-10 text-center text-sm text-slate-500">
            Belum ada pengiriman pada filter ini.
          </div>
        ) : (
          filteredItems.map((item) => {
            const currentIndex = statusSteps.indexOf(item.status);
            const nextStatus = getNextStatus(item.status);

            const progress =
              item.status === "bermasalah"
                ? 0
                : currentIndex >= 0
                ? ((currentIndex + 1) / statusSteps.length) * 100
                : 0;

            return (
              <div
                key={item.id}
                className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm"
              >
                <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
                  <div>
                    <div className="flex flex-wrap items-center gap-2">
                      <span
                        className={`rounded-full px-3 py-1 text-xs font-bold ${
                          statusColors[item.status] ||
                          "bg-slate-100 text-slate-700"
                        }`}
                      >
                        {statusLabels[item.status] || item.status}
                      </span>

                      {canMonitorAll && (
                        <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-bold text-slate-600">
                          {item.nama_sppg || "SPPG"}
                        </span>
                      )}

                      {(role === "admin" ||
                        role === "sppg" ||
                        role === "validator") && (
                        <span className="rounded-full bg-blue-50 px-3 py-1 text-xs font-bold text-blue-700">
                          Kode: {item.kode_konfirmasi || "-"}
                        </span>
                      )}
                    </div>

                    <h3 className="mt-3 text-lg font-black text-slate-950">
                      {item.nama_sekolah || "Sekolah Tujuan"}
                    </h3>

                    <div className="mt-2 flex flex-wrap gap-4 text-sm text-slate-500">
                      <span className="inline-flex items-center gap-1">
                        <MapPin className="h-4 w-4 text-blue-700" />
                        {item.tujuan_alamat || item.kabupaten || "-"}
                      </span>

                      <span className="inline-flex items-center gap-1">
                        <Utensils className="h-4 w-4 text-amber-700" />
                        {Number(item.jumlah_porsi || 0).toLocaleString(
                          "id-ID"
                        )}{" "}
                        porsi
                      </span>

                      <span className="inline-flex items-center gap-1">
                        <PackageCheck className="h-4 w-4 text-emerald-700" />
                        {Number(item.jumlah_omprengan || 0).toLocaleString(
                          "id-ID"
                        )}{" "}
                        omprengan
                      </span>
                    </div>

                    <div className="mt-3 text-sm text-slate-500">
                      Kurir: <b>{item.nama_kurir || "-"}</b> • Kendaraan:{" "}
                      <b>{item.kendaraan || "-"}</b> • Plat:{" "}
                      <b>{item.plat_nomor || "-"}</b>
                    </div>
                  </div>

                  {canShowActions && (
                    <div className="flex flex-wrap gap-2">
                      {role === "admin" && (
                        <StatusOverrideAdmin
                          pengirimanId={item.id}
                          currentStatus={item.status}
                          onUpdated={() => loadData(false)}
                        />
                      )}

                      {canUploadBukti && (
                        <UploadBuktiSPPG
                          pengirimanId={item.id}
                          onUploaded={() => loadData(false)}
                        />
                      )}

                      {canValidate && (
                        <ValidasiSekolahForm
                          pengirimanId={item.id}
                          jumlahPorsi={item.jumlah_porsi}
                          onValidated={() => loadData(false)}
                        />
                      )}

                      {canUpdateStatus &&
                        nextStatus &&
                        item.status !== "selesai" && (
                          <button
                            type="button"
                            onClick={() => updateStatus(item.id, nextStatus)}
                            disabled={savingId === item.id}
                            className="rounded-xl bg-blue-700 px-4 py-2 text-sm font-bold text-white hover:bg-blue-800 disabled:opacity-60"
                          >
                            {savingId === item.id
                              ? "Menyimpan..."
                              : `Lanjut: ${statusLabels[nextStatus]}`}
                          </button>
                        )}

                      {canUpdateStatus &&
                        item.status !== "bermasalah" &&
                        item.status !== "selesai" && (
                          <button
                            type="button"
                            onClick={() => updateStatus(item.id, "bermasalah")}
                            disabled={savingId === item.id}
                            className="rounded-xl bg-red-50 px-4 py-2 text-sm font-bold text-red-700 hover:bg-red-100 disabled:opacity-60"
                          >
                            Tandai Bermasalah
                          </button>
                        )}
                    </div>
                  )}
                </div>

                <div className="mt-5">
                  <div className="mb-2 flex items-center justify-between text-xs font-semibold text-slate-500">
                    <span>Progress Distribusi</span>
                    <span>{Math.round(progress)}%</span>
                  </div>

                  <div className="h-3 overflow-hidden rounded-full bg-slate-100">
                    <div
                      className={`h-full rounded-full ${
                        item.status === "bermasalah"
                          ? "bg-red-500"
                          : "bg-blue-700"
                      }`}
                      style={{ width: `${progress}%` }}
                    />
                  </div>

                  <div className="mt-3 grid grid-cols-2 gap-2 text-xs text-slate-500 md:grid-cols-4 lg:grid-cols-7">
                    {statusSteps.map((step) => {
                      const index = statusSteps.indexOf(step);
                      const done = currentIndex >= index;

                      return (
                        <div
                          key={step}
                          className={`rounded-xl px-2 py-2 text-center font-semibold ${
                            done ? "bg-blue-50 text-blue-700" : "bg-slate-50"
                          }`}
                        >
                          {statusLabels[step]}
                        </div>
                      );
                    })}
                  </div>
                </div>

                <div className="mt-4 grid grid-cols-1 gap-3 text-sm md:grid-cols-3">
                  <div className="rounded-2xl bg-slate-50 p-3">
                    <div className="flex items-center gap-2 font-bold text-slate-700">
                      <Clock className="h-4 w-4" />
                      Update Terakhir
                    </div>
                    <p className="mt-1 text-slate-500">
                      {formatDateTime(item.updated_at)}
                    </p>
                  </div>

                  <div className="rounded-2xl bg-slate-50 p-3">
                    <div className="flex items-center gap-2 font-bold text-slate-700">
                      <CheckCircle2 className="h-4 w-4" />
                      Jumlah Diterima
                    </div>
                    <p className="mt-1 text-slate-500">
                      {item.jumlah_diterima !== null
                        ? `${Number(item.jumlah_diterima || 0).toLocaleString(
                            "id-ID"
                          )} porsi`
                        : "Belum dikonfirmasi"}
                    </p>
                  </div>

                  <div className="rounded-2xl bg-slate-50 p-3">
                    <div className="flex items-center gap-2 font-bold text-slate-700">
                      <AlertTriangle className="h-4 w-4" />
                      Kondisi
                    </div>
                    <p className="mt-1 text-slate-500">
                      {item.validasi_kondisi &&
                      item.validasi_kondisi !== "belum"
                        ? item.validasi_kondisi
                        : item.kondisi_makanan || "Belum ada laporan"}
                    </p>
                  </div>
                </div>

                <div className="mt-4 rounded-2xl border border-slate-200 bg-slate-50 p-4">
                  <div className="mb-3 flex items-center gap-2 font-black text-slate-800">
                    <ImageIcon className="h-4 w-4 text-blue-700" />
                    Bukti & Validasi
                  </div>

                  <div className="grid grid-cols-1 gap-3 text-sm md:grid-cols-3">
                    <div className="rounded-xl bg-white p-3">
                      <p className="font-bold text-slate-700">
                        Foto Omprengan
                      </p>
                      {item.foto_omprengan ? (
                        <a
                          href={fileUrl(item.foto_omprengan)}
                          target="_blank"
                          rel="noreferrer"
                          className="mt-1 inline-block text-blue-700 underline"
                        >
                          Lihat bukti
                        </a>
                      ) : (
                        <p className="mt-1 text-slate-500">Belum diupload</p>
                      )}
                    </div>

                    <div className="rounded-xl bg-white p-3">
                      <p className="font-bold text-slate-700">Foto Menu</p>
                      {item.foto_menu ? (
                        <a
                          href={fileUrl(item.foto_menu)}
                          target="_blank"
                          rel="noreferrer"
                          className="mt-1 inline-block text-blue-700 underline"
                        >
                          Lihat bukti
                        </a>
                      ) : (
                        <p className="mt-1 text-slate-500">Belum diupload</p>
                      )}
                    </div>

                    <div className="rounded-xl bg-white p-3">
                      <p className="font-bold text-slate-700">
                        Foto Penerimaan
                      </p>
                      {item.foto_penerimaan ? (
                        <a
                          href={fileUrl(item.foto_penerimaan)}
                          target="_blank"
                          rel="noreferrer"
                          className="mt-1 inline-block text-blue-700 underline"
                        >
                          Lihat bukti
                        </a>
                      ) : (
                        <p className="mt-1 text-slate-500">Belum divalidasi</p>
                      )}
                    </div>
                  </div>

                  <div className="mt-3 grid grid-cols-1 gap-3 text-sm md:grid-cols-3">
                    <div className="rounded-xl bg-white p-3">
                      <p className="font-bold text-slate-700">Validasi Menu</p>
                      <p className="mt-1 text-slate-500">
                        {item.validasi_menu || "belum"}
                      </p>
                    </div>

                    <div className="rounded-xl bg-white p-3">
                      <p className="font-bold text-slate-700">
                        Validasi Jumlah
                      </p>
                      <p className="mt-1 text-slate-500">
                        {item.validasi_jumlah || "belum"}
                      </p>
                    </div>

                    <div className="rounded-xl bg-white p-3">
                      <p className="font-bold text-slate-700">
                        Catatan Validasi
                      </p>
                      <p className="mt-1 text-slate-500">
                        {item.catatan_validasi || "-"}
                      </p>
                    </div>
                  </div>
                </div>
              </div>
            );
          })
        )}
      </div>
    </section>
  );
}