import { useEffect, useState } from "react";
import {
  CalendarRange,
  RefreshCw,
  BarChart3,
  AlertTriangle,
  CheckCircle2,
  MapPin,
  Building2,
  Search,
  Utensils,
} from "lucide-react";

const REKAP_API = "http://openplate.my.id/api/tracking/rekap-filter.php";
const OPTIONS_API = "http://openplate.my.id/api/tracking/rekap-options.php";

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

export default function RekapPengirimanFilter() {
  const [periode, setPeriode] = useState("mingguan");
  const [provinsi, setProvinsi] = useState("");
  const [kabupaten, setKabupaten] = useState("");
  const [sppgId, setSppgId] = useState("");
  const [searchSppg, setSearchSppg] = useState("");

  const [options, setOptions] = useState({
    provinsi: [],
    kabupaten: [],
    sppg: [],
  });

  const [data, setData] = useState({
    tanggal_mulai: "",
    tanggal_selesai: "",
    summary: {
      total_pengiriman: 0,
      total_porsi: 0,
      total_tervalidasi: 0,
      total_bermasalah: 0,
      bukti_omprengan: 0,
      bukti_menu: 0,
      bukti_penerimaan: 0,
    },
    items: [],
  });

  const [loading, setLoading] = useState(false);
  const [loadingOptions, setLoadingOptions] = useState(false);

  const loadOptions = async () => {
    try {
      setLoadingOptions(true);

      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) {
        setOptions({
          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 filter:", err);
    } finally {
      setLoadingOptions(false);
    }
  };

  const loadRekap = async () => {
    try {
      setLoading(true);

      const params = new URLSearchParams({ periode });
      if (provinsi) params.set("provinsi", provinsi);
      if (kabupaten) params.set("kabupaten", kabupaten);
      if (sppgId) params.set("sppg_id", sppgId);

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

      if (result.success) {
        setData({
          tanggal_mulai: result.data?.tanggal_mulai || "",
          tanggal_selesai: result.data?.tanggal_selesai || "",
          summary: result.data?.summary || data.summary,
          items: Array.isArray(result.data?.items) ? result.data.items : [],
        });
      }
    } catch (err) {
      console.error("Gagal mengambil rekap:", err);
    } finally {
      setLoading(false);
    }
  };

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

  useEffect(() => {
    loadRekap();
  }, [periode, provinsi, kabupaten, sppgId]);

  const filteredSppgOptions = options.sppg.filter((item) => {
    const keyword = searchSppg.trim().toLowerCase();
    if (!keyword) return true;

    return [item.nama, item.kabupaten, item.provinsi]
      .join(" ")
      .toLowerCase()
      .includes(keyword);
  });

  const summary = data.summary || {};

  return (
    <section className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm">
      <div className="mb-5 flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
        <div>
          <div className="inline-flex items-center gap-2 rounded-full bg-purple-50 px-3 py-1 text-xs font-bold text-purple-700">
            <CalendarRange className="h-4 w-4" />
            Rekap Pengiriman Terfilter
          </div>

          <h2 className="mt-3 text-xl font-black text-slate-950">
            Rekap {periode === "mingguan" ? "Mingguan" : "Bulanan"}
          </h2>

          <p className="mt-1 text-sm text-slate-500">
            Pilih provinsi, kabupaten/kota, lalu SPPG agar rekap lebih mudah dicari.
          </p>

          <p className="mt-1 text-xs font-semibold text-slate-400">
            Periode {data.tanggal_mulai || "-"} sampai {data.tanggal_selesai || "-"}
          </p>
        </div>

        <button
          type="button"
          onClick={loadRekap}
          className="inline-flex w-fit items-center gap-2 rounded-xl border border-slate-200 px-3 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="mb-5 grid grid-cols-1 gap-3 lg:grid-cols-4">
        <select
          value={periode}
          onChange={(e) => setPeriode(e.target.value)}
          className="rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold outline-none"
        >
          <option value="mingguan">Mingguan</option>
          <option value="bulanan">Bulanan</option>
        </select>

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

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

        <select
          value={sppgId}
          onChange={(e) => setSppgId(e.target.value)}
          className="rounded-xl border border-slate-200 px-3 py-2 text-sm font-semibold outline-none"
        >
          <option value="">
            {loadingOptions ? "Mengambil SPPG..." : "Semua SPPG"}
          </option>
          {filteredSppgOptions.map((item) => (
            <option key={item.id} value={item.id}>
              {item.nama} - {item.kabupaten}
            </option>
          ))}
        </select>
      </div>

      <div className="mb-5">
        <div className="relative">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
          <input
            value={searchSppg}
            onChange={(e) => setSearchSppg(e.target.value)}
            placeholder="Cari nama SPPG lebih cepat..."
            className="w-full rounded-xl border border-slate-200 py-2 pl-10 pr-3 text-sm outline-none"
          />
        </div>
      </div>

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

        <div className="rounded-2xl bg-amber-50 p-4">
          <Utensils className="mb-2 h-5 w-5 text-amber-700" />
          <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 className="rounded-2xl bg-emerald-50 p-4">
          <CheckCircle2 className="mb-2 h-5 w-5 text-emerald-700" />
          <p className="text-sm font-semibold text-emerald-700">Tervalidasi</p>
          <p className="mt-1 text-2xl font-black text-emerald-700">
            {summary.total_tervalidasi || 0}
          </p>
        </div>

        <div className="rounded-2xl bg-red-50 p-4">
          <AlertTriangle className="mb-2 h-5 w-5 text-red-700" />
          <p className="text-sm font-semibold text-red-700">Bermasalah</p>
          <p className="mt-1 text-2xl font-black text-red-700">
            {summary.total_bermasalah || 0}
          </p>
        </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 font-semibold text-slate-600">
          Bukti Omprengan: {summary.bukti_omprengan || 0}
        </div>
        <div className="rounded-2xl bg-slate-50 p-3 font-semibold text-slate-600">
          Bukti Menu: {summary.bukti_menu || 0}
        </div>
        <div className="rounded-2xl bg-slate-50 p-3 font-semibold text-slate-600">
          Bukti Penerimaan: {summary.bukti_penerimaan || 0}
        </div>
      </div>

      <div className="mt-5 rounded-2xl border border-slate-200">
        <div className="border-b border-slate-200 px-4 py-3">
          <h3 className="font-black text-slate-900">Detail Pengiriman</h3>
          <p className="text-xs text-slate-500">
            Menampilkan maksimal 100 data terbaru sesuai filter.
          </p>
        </div>

        <div className="max-h-80 overflow-auto">
          {data.items.length === 0 ? (
            <div className="p-8 text-center text-sm text-slate-500">
              Belum ada data pada filter ini.
            </div>
          ) : (
            <div className="divide-y divide-slate-200">
              {data.items.map((item) => (
                <div key={item.id} className="grid grid-cols-1 gap-2 p-4 text-sm lg:grid-cols-[1.2fr_1fr_1fr_120px]">
                  <div>
                    <p className="font-black text-slate-900">
                      {item.nama_sppg || "SPPG"}
                    </p>
                    <p className="mt-1 text-slate-500">
                      <Building2 className="mr-1 inline h-4 w-4" />
                      {item.nama_sekolah || "-"}
                    </p>
                  </div>

                  <div className="text-slate-500">
                    <MapPin className="mr-1 inline h-4 w-4" />
                    {item.kabupaten || "-"}, {item.provinsi || "-"}
                  </div>

                  <div className="text-slate-500">
                    {Number(item.jumlah_porsi || 0).toLocaleString("id-ID")} porsi
                    {item.jumlah_diterima !== null && (
                      <span> • diterima {Number(item.jumlah_diterima || 0).toLocaleString("id-ID")}</span>
                    )}
                  </div>

                  <div>
                    <span className={`rounded-full px-3 py-1 text-xs font-bold ${
                      item.status === "selesai"
                        ? "bg-emerald-100 text-emerald-700"
                        : item.status === "bermasalah"
                        ? "bg-red-100 text-red-700"
                        : "bg-blue-100 text-blue-700"
                    }`}>
                      {statusLabels[item.status] || item.status}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </section>
  );
}
