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

const LIST_API = "http://localhost/backend/api/tracking/list.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",
  });
};

export default function TrackingPublik() {
  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 [search, setSearch] = useState("");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

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

      const params = new URLSearchParams({
        role: "publik",
        tanggal,
        status: "semua",
      });

      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 tracking publik.");
        setItems([]);
        return;
      }

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

  useEffect(() => {
    loadData();

    const interval = setInterval(() => loadData(false), 5000);
    return () => clearInterval(interval);
  }, [tanggal]);

  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.status,
      ]
        .join(" ")
        .toLowerCase();

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

  return (
    <div className="min-h-screen bg-slate-50">
      <section className="px-4 pt-4 sm:px-6 lg:px-8">
        <div className="relative mx-auto max-w-7xl overflow-hidden rounded-[2.25rem] border border-white/10 bg-gradient-to-br from-[#23486b] via-[#2450d3] to-[#1b8d93] text-white shadow-[0_20px_70px_rgba(2,8,23,0.22)]">
          <div className="pointer-events-none absolute inset-0 bg-[linear-gradient(rgba(255,255,255,0.06)_1px,transparent_1px),linear-gradient(90deg,rgba(255,255,255,0.06)_1px,transparent_1px)] bg-[size:70px_70px] opacity-45" />
          <div className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top_left,rgba(255,255,255,0.16),transparent_28%),radial-gradient(circle_at_top_right,rgba(96,165,250,0.18),transparent_24%),radial-gradient(circle_at_bottom_right,rgba(45,212,191,0.16),transparent_28%)]" />

          <div className="relative z-10 px-5 py-10 text-center sm:px-8 sm:py-12 lg:px-12 lg:py-16">
            <div className="inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/10 px-5 py-2 text-sm font-bold uppercase tracking-[0.18em] text-blue-50 shadow-lg backdrop-blur-md">
              <Truck className="h-4 w-4 text-cyan-200" />
              Tracking Distribusi
            </div>

            <h1 className="mx-auto mt-6 max-w-full whitespace-nowrap text-3xl font-black leading-[1.05] tracking-tight text-white drop-shadow-[0_4px_16px_rgba(0,0,0,0.25)] sm:text-4xl lg:text-5xl xl:text-6xl">
              <span className="text-white">Tracking </span>
              <span className="bg-gradient-to-r from-cyan-200 via-sky-100 to-teal-200 bg-clip-text text-transparent">
                Distribusi MBG
              </span>
            </h1>

            <p className="mx-auto mt-5 max-w-4xl text-base leading-relaxed text-blue-50/90 sm:text-lg lg:text-xl">
              Pantau status umum distribusi makanan bergizi secara transparan tanpa menampilkan data internal seperti kode konfirmasi atau detail kurir.
            </p>

            <div className="mt-8 flex justify-center">
              <button
                type="button"
                onClick={() => loadData(true)}
                className="inline-flex items-center justify-center gap-2 rounded-full border border-white/25 bg-white/10 px-6 py-3 text-sm font-bold text-white shadow-lg backdrop-blur-md transition hover:bg-white/20"
              >
                <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
                Refresh Data
              </button>
            </div>

            <div className="mt-8 grid grid-cols-2 gap-4 lg:grid-cols-4">
              <div className="rounded-2xl border border-white/10 bg-white/12 p-4 backdrop-blur">
                <p className="text-sm font-medium text-blue-100">Total Pengiriman</p>
                <p className="mt-2 text-3xl font-black">{summary.total_pengiriman}</p>
              </div>
              <div className="rounded-2xl border border-white/10 bg-white/12 p-4 backdrop-blur">
                <p className="text-sm font-medium text-blue-100">Sedang Berjalan</p>
                <p className="mt-2 text-3xl font-black">{summary.berjalan}</p>
              </div>
              <div className="rounded-2xl border border-white/10 bg-white/12 p-4 backdrop-blur">
                <p className="text-sm font-medium text-blue-100">Selesai</p>
                <p className="mt-2 text-3xl font-black">{summary.selesai}</p>
              </div>
              <div className="rounded-2xl border border-white/10 bg-white/12 p-4 backdrop-blur">
                <p className="text-sm font-medium text-blue-100">Total Porsi</p>
                <p className="mt-2 text-3xl font-black">
                  {Number(summary.total_porsi || 0).toLocaleString("id-ID")}
                </p>
              </div>
            </div>
          </div>
        </div>
      </section>

      <main className="mx-auto max-w-7xl space-y-6 px-4 py-8 sm:px-6 lg:px-8">
        <div className="rounded-[1.75rem] border border-slate-200/80 bg-white p-5 shadow-sm shadow-slate-200/70">
          <div className="grid grid-cols-1 gap-3 md:grid-cols-[180px_1fr_auto]">
            <input
              type="date"
              value={tanggal}
              onChange={(e) => setTanggal(e.target.value)}
              className="rounded-2xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm font-medium text-slate-700 outline-none transition focus:border-blue-400 focus:bg-white focus:ring-4 focus:ring-blue-100"
            />

            <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 SPPG, sekolah, kabupaten, atau provinsi..."
                className="w-full rounded-2xl border border-slate-200 bg-slate-50 py-3 pl-10 pr-4 text-sm font-medium text-slate-700 outline-none transition placeholder:text-slate-400 focus:border-blue-400 focus:bg-white focus:ring-4 focus:ring-blue-100"
              />
            </div>

            <button
              type="button"
              onClick={() => loadData(true)}
              className="inline-flex items-center justify-center gap-2 rounded-2xl border border-slate-200 bg-white px-5 py-3 text-sm font-bold text-slate-700 shadow-sm transition hover:bg-slate-50"
            >
              <RefreshCw className={`h-4 w-4 ${loading ? "animate-spin" : ""}`} />
              Refresh
            </button>
          </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="grid grid-cols-1 gap-4 lg:grid-cols-2">
          {loading ? (
            <div className="rounded-[1.75rem] border border-slate-200 bg-white p-10 text-center text-sm font-medium text-slate-500 shadow-sm lg:col-span-2">
              Mengambil data tracking...
            </div>
          ) : filteredItems.length === 0 ? (
            <div className="rounded-[1.75rem] border border-slate-200 bg-white p-10 text-center text-sm font-medium text-slate-500 shadow-sm lg:col-span-2">
              Belum ada tracking pengiriman pada tanggal ini.
            </div>
          ) : (
            filteredItems.map((item) => {
              const currentIndex = statusSteps.indexOf(item.status);
              const progress =
                item.status === "bermasalah"
                  ? 0
                  : currentIndex >= 0
                  ? ((currentIndex + 1) / statusSteps.length) * 100
                  : 0;

              return (
                <div key={item.id} className="group rounded-[1.75rem] border border-slate-200 bg-white p-5 shadow-sm shadow-slate-200/70 transition hover:-translate-y-1 hover:shadow-xl hover:shadow-slate-200/80">
                  <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>

                    {item.status === "bermasalah" && (
                      <span className="inline-flex items-center gap-1 rounded-full bg-red-50 px-3 py-1 text-xs font-bold text-red-700">
                        <AlertTriangle className="h-3.5 w-3.5" />
                        Perlu Tindak Lanjut
                      </span>
                    )}
                  </div>

                  <h3 className="mt-4 text-xl font-black tracking-tight 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.kabupaten || "-"}, {item.provinsi || "-"}
                    </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>
                  </div>

                  <p className="mt-3 text-sm text-slate-500">
                    SPPG pengirim: <b>{item.nama_sppg || "-"}</b>
                  </p>

                  <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 ring-1 ring-slate-200/70">
                      <div
                        className={`h-full rounded-full transition-all duration-500 ${item.status === "bermasalah" ? "bg-red-500" : "bg-gradient-to-r from-blue-700 to-cyan-500"}`}
                        style={{ width: `${progress}%` }}
                      />
                    </div>
                  </div>

                  <div className="mt-4 grid grid-cols-1 gap-3 text-sm md:grid-cols-2">
                    <div className="rounded-2xl border border-slate-100 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 border border-slate-100 bg-slate-50 p-3">
                      <div className="flex items-center gap-2 font-bold text-slate-700">
                        <CheckCircle2 className="h-4 w-4" />
                        Status Penerimaan
                      </div>
                      <p className="mt-1 text-slate-500">
                        {item.status === "selesai" ? "Sudah selesai" : "Dalam proses"}
                      </p>
                    </div>
                  </div>
                </div>
              );
            })
          )}
        </div>
      </main>
    </div>
  );
}
