"use client";

import { useState, useEffect } from "react";
import dynamic from "next/dynamic";
import type { StyleFunction } from "leaflet";
import { MapPin, ChevronRight, Users, X, Loader2 } from "lucide-react";

import dataWilayah from "../data/indonesia-wilayah-5.json";
import { publicRegionApi, type Region, type Tbm } from "@/lib/api/public";

interface RegionDetail {
  region: Region;
  permanent: Tbm[];
  reviewer: Tbm[];
  initiation: Tbm[];
}

const REGION_COLORS = [
  "#3B82F6", 
  "#EF4444", 
  "#FACC15", 
  "#22C55E", 
  "#8B5CF6", 
];

function getRegionColor(index: number): string {
  return REGION_COLORS[index] ?? "#CBD5E1";
}

const LeafletMap = dynamic(() => import("./LeafletMap"), { ssr: false });

export default function PetaSebaranMap() {
  const [regions, setRegions] = useState<Region[]>([]);
  const [regionDetails, setRegionDetails] = useState<Record<number, RegionDetail>>({});
  const [selectedRegionId, setSelectedRegionId] = useState<number | null>(null);
  const [showDetail, setShowDetail] = useState(false);
  const [loading, setLoading] = useState(true);
  const [loadingDetail, setLoadingDetail] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const regionColorMap = Object.fromEntries(
    regions.map((r, i) => [r.name, getRegionColor(i)])
  );

  useEffect(() => {
    publicRegionApi
      .getAll()
      .then((res) => setRegions(res.data))
      .catch((e) => setError(e.message ?? "Gagal memuat data wilayah"))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => {
    if (selectedRegionId === null) return;
    if (regionDetails[selectedRegionId]) return;

    setLoadingDetail(true);
    publicRegionApi
      .getById(selectedRegionId)
      .then((res) => {
        const tbms = res.data.tbms ?? [];
        setRegionDetails((prev) => ({
          ...prev,
          [selectedRegionId]: {
            region: res.data,
            permanent: tbms.filter((t) => t.type === "permanent"),
            reviewer: tbms.filter((t) => t.type === "reviewer"),
            initiation: tbms.filter((t) => t.type === "initiation"),
          },
        }));
      })
      .catch((e) => setError(e.message ?? "Gagal memuat data TBM"))
      .finally(() => setLoadingDetail(false));
  }, [selectedRegionId]);

  const selectedRegion = regions.find((r) => r.id === selectedRegionId) ?? null;
  const selectedColor = selectedRegion
    ? getRegionColor(regions.indexOf(selectedRegion))
    : "#CBD5E1";
  const selectedDetail = selectedRegionId ? regionDetails[selectedRegionId] : null;

  const styleWilayah: StyleFunction = (feature) => {
    const namaWilayah = feature?.properties?.wilayah as string;
    return {
      fillColor: regionColorMap[namaWilayah] ?? "#CBD5E1",
      weight: 1,
      color: "#fff",
      fillOpacity: 0.7,
    };
  };

  const onEachWilayah = (feature: any, layer: any) => {
    const namaWilayah = feature.properties?.wilayah as string;
    const namaProvinsi = feature.properties?.provinsi;

    layer.on({
      click: () => {
        const region = regions.find((r) => r.name === namaWilayah);
        if (region) setSelectedRegionId(region.id);
        layer
          .bindPopup(`<strong>${namaWilayah}</strong><br/><small>${namaProvinsi}</small>`)
          .openPopup();
      },
      mouseover: () => layer.setStyle({ fillOpacity: 0.9, weight: 2 }),
      mouseout: () => layer.setStyle({ fillOpacity: 0.7, weight: 1 }),
    });
  };

  const handleLihatDetail = () => {
    if (selectedRegionId) setShowDetail(true);
  };

  const handleKembali = () => {
    setShowDetail(false);
    setSelectedRegionId(null);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64 gap-2 text-gray-500">
        <Loader2 className="w-5 h-5 animate-spin" />
        <span>Memuat data wilayah...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64 text-red-500">
        <p>Gagal memuat data: {error}</p>
      </div>
    );
  }

  return (
    <div className="space-y-8">
      <div className="text-center">
        <div className="flex items-center justify-center gap-2 mb-2">
          <MapPin className="hidden lg:block w-6 h-6 text-brand" />
          <h3 className="text-2xl font-bold text-brand">Peta Kekuatan Medis PTBMMKI</h3>
        </div>
        <p className="text-gray-600">
          Tersebar di <span className="font-bold">38 provinsi</span> seluruh Indonesia
        </p>
      </div>

      <div className="border-t border-gray-200 pt-6">
        <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
          {showDetail && selectedDetail ? (
            <DetailWilayah
              detail={selectedDetail}
              warna={selectedColor}
              onBack={handleKembali}
            />
          ) : (
            <>
              <div className="relative w-full h-[420px]">
                <LeafletMap
                  dataWilayah={dataWilayah}
                  styleWilayah={styleWilayah}
                  onEachWilayah={onEachWilayah}
                />
                <LegendWilayah regions={regions} colorMap={regionColorMap} />
              </div>

              {selectedRegion && (
                <div className="border-t border-gray-200 p-6">
                  {loadingDetail ? (
                    <div className="flex items-center gap-2 text-gray-400">
                      <Loader2 className="w-4 h-4 animate-spin" />
                      <span className="text-sm">Memuat data TBM...</span>
                    </div>
                  ) : (
                    <>
                      <div className="flex items-center justify-between mb-4">
                        <div className="flex items-center gap-3">
                          <div
                            className="w-10 h-10 rounded-full flex items-center justify-center text-white font-bold"
                            style={{ backgroundColor: selectedColor }}
                          >
                            {selectedRegion.id}
                          </div>
                          <h4 className="font-bold text-gray-800">{selectedRegion.name}</h4>
                        </div>
                        <div
                          className="px-4 py-2 rounded-lg font-bold text-white"
                          style={{ backgroundColor: selectedColor }}
                        >
                          {selectedRegion.total_tbms} TBM
                        </div>
                      </div>

                      <p className="text-gray-600 text-sm mb-4 line-clamp-2">
                        {selectedRegion.description}
                      </p>

                      <button
                        onClick={handleLihatDetail}
                        className="w-full py-3 bg-brand text-white rounded-lg hover:bg-brand/90 transition-colors flex items-center justify-center gap-2 cursor-pointer"
                      >
                        <span>Lihat Detail Wilayah</span>
                        <ChevronRight className="w-4 h-4" />
                      </button>
                    </>
                  )}
                </div>
              )}

              <div className="border-t border-gray-200 p-6">
                <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
                  {regions.map((region, index) => {
                    const warna = getRegionColor(index);
                    return (
                      <div
                        key={region.id}
                        className="bg-white rounded-lg p-3 border border-gray-200 hover:shadow-sm transition-all text-center cursor-pointer"
                        onClick={() => setSelectedRegionId(region.id)}
                      >
                        <div
                          className="w-12 h-12 rounded-full mx-auto mb-2 flex items-center justify-center text-white font-bold"
                          style={{ backgroundColor: warna }}
                        >
                          {region.id}
                        </div>
                        <h5 className="font-bold text-gray-800 text-sm mb-1">{region.name}</h5>
                        <p className="text-xs text-gray-400">{region.total_tbms} TBM</p>
                      </div>
                    );
                  })}
                </div>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

function DetailWilayah({
  detail,
  warna,
  onBack,
}: {
  detail: RegionDetail;
  warna: string;
  onBack: () => void;
}) {
  const { region, permanent, reviewer, initiation } = detail;

  return (
    <div className="p-6">
      <div className="flex justify-between items-center mb-6">
        <button onClick={onBack} className="flex items-center gap-2 text-brand cursor-pointer">
          <ChevronRight className="w-5 h-5 rotate-180" />
          Kembali ke Peta
        </button>
        <button onClick={onBack} className="p-2 hover:bg-gray-100 rounded-lg cursor-pointer">
          <X className="w-5 h-5" />
        </button>
      </div>

      <div className="mb-6">
        <div className="flex items-center gap-3 mb-4">
          <div
            className="w-12 h-12 rounded-full flex items-center justify-center text-white font-bold"
            style={{ backgroundColor: warna }}
          >
            <span className="text-xl">{region.id}</span>
          </div>
          <h4 className="text-xl font-bold text-gray-800">{region.name}</h4>
        </div>

        <div
          className="px-4 py-2 rounded-lg inline-block mb-4 text-white"
          style={{ backgroundColor: warna }}
        >
          <span className="text-2xl font-bold">{region.total_tbms} TBM</span>
        </div>

        <p className="text-gray-700 mb-6">{region.description}</p>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <TbmList title="Anggota Tetap" items={permanent} />
          <TbmList title="Anggota Peninjau" items={reviewer} />
          <div className="md:col-span-2">
            <TbmList title="Anggota Inisiasi" items={initiation} />
          </div>
        </div>
      </div>
    </div>
  );
}

function TbmList({ title, items }: { title: string; items: Tbm[] }) {
  return (
    <div className="bg-white rounded-lg p-4 border border-gray-200">
      <div className="flex items-center gap-2 mb-3">
        <Users className="w-5 h-5 text-brand" />
        <h5 className="font-bold text-gray-800">{title}</h5>
        <span className="ml-auto text-xs text-gray-400">{items.length}</span>
      </div>
      {items.length === 0 ? (
        <p className="text-gray-400 text-sm italic">Tidak ada data</p>
      ) : (
        <ul className="space-y-2">
          {items.map((tbm) => (
            <li key={tbm.id} className="flex items-start">
              <span className="text-brand mr-2">•</span>
              <span className="text-gray-600 text-sm">{tbm.tbm}</span>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}

function LegendWilayah({
  regions,
  colorMap,
}: {
  regions: Region[];
  colorMap: Record<string, string>;
}) {
  return (
    <div className="absolute bottom-4 left-4 bg-white rounded-lg shadow-sm p-3 text-sm z-[1000] border border-gray-200">
      <div className="font-bold mb-2 text-gray-800">Legenda Wilayah</div>
      {regions.map((region) => (
        <div key={region.id} className="flex items-center gap-2 mb-1">
          <span
            className="w-4 h-4 rounded border border-gray-300 flex-shrink-0"
            style={{ backgroundColor: colorMap[region.name] ?? "#CBD5E1" }}
          />
          <span className="text-gray-600 text-xs lg:text-sm">{region.name}</span>
        </div>
      ))}
    </div>
  );
}