import { useEffect, useMemo, useState } from "react";
import {
  Trophy,
  Star,
  MessageSquare,
  RefreshCw,
  MapPin,
  ShieldCheck,
  ThumbsUp,
  Search,
  ChevronDown,
} from "lucide-react";
import { Link } from "react-router-dom";

const API_URL = "http://openplate.my.id/api/sppg-ranking/top-per-provinsi.php";

const medalStyle = [
  "bg-amber-400 text-white",
  "bg-slate-300 text-slate-700",
  "bg-orange-300 text-orange-900",
];

const formatNumber = (value) => Number(value || 0).toLocaleString("id-ID");

export default function SPPGBestByProvince({ defaultProvinsi = "", limit = 3 }) {
  const [data, setData] = useState([]);
  const [selectedProvinsi, setSelectedProvinsi] = useState(defaultProvinsi);
  const [searchProvinsi, setSearchProvinsi] = useState("");
  const [showDropdown, setShowDropdown] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const loadRanking = async () => {
    try {
      setLoading(true);
      setError("");

      const params = new URLSearchParams();
      params.set("limit", String(limit));

      const res = await fetch(`${API_URL}?${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 ranking SPPG.");
        setData([]);
        return;
      }

      const nextData = Array.isArray(result.data) ? result.data : [];
      setData(nextData);

      if (!selectedProvinsi && nextData.length > 0) {
        setSelectedProvinsi(nextData[0].provinsi);
      }
    } catch (err) {
      console.error("Gagal mengambil ranking SPPG:", err);
      setError("Gagal mengambil data SPPG terbaik dari server.");
      setData([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadRanking();

    const interval = setInterval(loadRanking, 30000);
    return () => clearInterval(interval);
  }, [limit]);

  const provinsiOptions = useMemo(() => {
    return data.map((group) => group.provinsi).filter(Boolean);
  }, [data]);

  const filteredProvinsiOptions = useMemo(() => {
    const keyword = searchProvinsi.trim().toLowerCase();

    if (!keyword) {
      return provinsiOptions;
    }

    return provinsiOptions.filter((provinsi) =>
      provinsi.toLowerCase().includes(keyword)
    );
  }, [provinsiOptions, searchProvinsi]);

  const selectedGroup = useMemo(() => {
    if (!selectedProvinsi && data.length > 0) {
      return data[0];
    }

    return data.find((group) => group.provinsi === selectedProvinsi) || null;
  }, [data, selectedProvinsi]);

  const handleSelectProvinsi = (provinsi) => {
    setSelectedProvinsi(provinsi);
    setSearchProvinsi("");
    setShowDropdown(false);
  };

  return (
    <section className="rounded-3xl border border-amber-200 bg-amber-50/70 p-6 shadow-sm">
      <div className="mb-5 flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
        <div className="flex items-start gap-3">
          <div className="flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-2xl bg-amber-400 text-white shadow-sm">
            <Trophy className="h-7 w-7" />
          </div>

          <div>
            <h2 className="text-2xl font-black text-amber-900">
              SPPG Terbaik Bulan Ini
            </h2>
            <p className="mt-1 text-sm font-medium text-amber-700">
              Pilih satu provinsi untuk melihat 3 SPPG terbaik berdasarkan penilaian masyarakat, pengaduan selesai, dan validasi Pihak Sekolah.
            </p>
          </div>
        </div>

        <button
          type="button"
          onClick={loadRanking}
          className="inline-flex w-fit items-center gap-2 rounded-xl border border-amber-200 bg-white px-3 py-2 text-xs font-bold text-amber-700 shadow-sm transition hover:bg-amber-50"
        >
          <RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
          Refresh
        </button>
      </div>

      <div className="mb-5 rounded-2xl border border-amber-100 bg-white p-4">
        <div className="mb-2 flex items-center gap-2 text-sm font-bold text-slate-800">
          <MapPin className="h-4 w-4 text-amber-600" />
          Pilih Provinsi
        </div>

        <div className="relative">
          <button
            type="button"
            onClick={() => setShowDropdown((prev) => !prev)}
            className="flex w-full items-center justify-between rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-left text-sm font-bold text-slate-800 transition hover:bg-slate-100"
          >
            <span>{selectedGroup?.provinsi || "Pilih provinsi"}</span>
            <ChevronDown className="h-4 w-4 text-slate-500" />
          </button>

          {showDropdown && (
            <div className="absolute z-20 mt-2 w-full overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-xl">
              <div className="flex items-center gap-2 border-b border-slate-100 px-3 py-2">
                <Search className="h-4 w-4 text-slate-400" />
                <input
                  value={searchProvinsi}
                  onChange={(e) => setSearchProvinsi(e.target.value)}
                  placeholder="Cari provinsi..."
                  className="w-full bg-transparent py-2 text-sm outline-none placeholder:text-slate-400"
                  autoFocus
                />
              </div>

              <div className="max-h-64 overflow-y-auto p-2">
                {filteredProvinsiOptions.length === 0 ? (
                  <div className="px-3 py-5 text-center text-sm text-slate-500">
                    Provinsi tidak ditemukan.
                  </div>
                ) : (
                  filteredProvinsiOptions.map((provinsi) => (
                    <button
                      key={provinsi}
                      type="button"
                      onClick={() => handleSelectProvinsi(provinsi)}
                      className={`block w-full rounded-xl px-3 py-2 text-left text-sm font-semibold transition ${
                        selectedProvinsi === provinsi
                          ? "bg-amber-100 text-amber-800"
                          : "text-slate-700 hover:bg-slate-50"
                      }`}
                    >
                      {provinsi}
                    </button>
                  ))
                )}
              </div>
            </div>
          )}
        </div>
      </div>

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

      {loading ? (
        <div className="rounded-2xl bg-white px-4 py-10 text-center text-sm text-slate-500">
          Mengambil data ranking SPPG...
        </div>
      ) : !selectedGroup ? (
        <div className="rounded-2xl bg-white px-4 py-10 text-center text-sm text-slate-500">
          Belum ada data ranking. Tambahkan penilaian masyarakat dan validasi Pihak Sekolah.
        </div>
      ) : (
        <div className="rounded-3xl bg-white p-5 shadow-sm">
          <div className="mb-4 flex items-center gap-2">
            <MapPin className="h-5 w-5 text-amber-600" />
            <h3 className="text-lg font-black text-slate-900">
              {selectedGroup.provinsi}
            </h3>
          </div>

          {selectedGroup.items.length === 0 ? (
            <div className="rounded-2xl bg-slate-50 px-4 py-10 text-center text-sm text-slate-500">
              Belum ada SPPG ranking pada provinsi ini.
            </div>
          ) : (
            <div className="space-y-3">
              {selectedGroup.items.map((item, index) => (
                <Link
                  key={item.id}
                  to={`/detail-sppg/${item.id}`}
                  className="block rounded-2xl border border-slate-100 bg-slate-50 px-4 py-4 transition hover:-translate-y-0.5 hover:border-amber-200 hover:bg-amber-50/50 hover:shadow-sm"
                >
                  <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <div className="flex items-start gap-4">
                      <div
                        className={`flex h-12 w-12 flex-shrink-0 items-center justify-center rounded-2xl font-black ${
                          medalStyle[index] || "bg-slate-100 text-slate-600"
                        }`}
                      >
                        #{index + 1}
                      </div>

                      <div>
                        <h4 className="font-black text-slate-900">
                          {item.nama}
                        </h4>
                        <p className="text-sm text-slate-500">
                          {item.kabupaten || "-"}
                        </p>

                        <div className="mt-2 flex flex-wrap items-center gap-3 text-sm">
                          <span className="inline-flex items-center gap-1 font-semibold text-amber-600">
                            <Star className="h-4 w-4 fill-amber-400 text-amber-400" />
                            {item.rating}/5 ({formatNumber(item.total_ulasan)} ulasan)
                          </span>

                          <span className="inline-flex items-center gap-1 font-semibold text-blue-600">
                            <MessageSquare className="h-4 w-4" />
                            {formatNumber(item.pengaduan_selesai)}/{formatNumber(item.total_pengaduan)} pengaduan selesai
                          </span>

                          <span className="inline-flex items-center gap-1 font-semibold text-emerald-600">
                            <ShieldCheck className="h-4 w-4" />
                            {formatNumber(item.validasi_sesuai)}/{formatNumber(item.total_validasi)} validasi sesuai
                          </span>
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center gap-2 text-emerald-700">
                      <ThumbsUp className="h-5 w-5" />
                      <span className="text-xl font-black">
                        {item.skor}
                      </span>
                      <span className="text-sm font-semibold text-slate-400">
                        /100
                      </span>
                    </div>
                  </div>
                </Link>
              ))}
            </div>
          )}
        </div>
      )}
    </section>
  );
}
