"use client";

import { useEffect, useMemo } from "react";
import { Marker, Polyline, Polygon, Tooltip, useMap } from "react-leaflet";
import type { Desa } from "@/lib/types";
import { parsePath, type LatLng } from "@/lib/gpx";
import { MapShell, Recenter, pointIcon } from "@/components/map/map-shell";

const DEFAULT_CENTER: LatLng = [-7.3841, 109.0363];

function hex(value: string | null | undefined, cadangan: string) {
  return value && /^#[0-9a-fA-F]{6}$/.test(value) ? value : cadangan;
}

function Sesuaikan({ titik }: { titik: LatLng[] }) {
  const map = useMap();
  useEffect(() => {
    if (titik.length > 1) map.fitBounds(titik, { padding: [24, 24] });
  }, [map, titik]);
  return null;
}

export function PetaWilayahDesa({ desa }: { desa: Desa }) {
  const titik = useMemo(() => parsePath(desa.wilayahPath), [desa.wilayahPath]);
  const warna = hex(desa.wilayahWarna, "#0f766e");
  const pinggir = hex(desa.wilayahBorder, "#134e4a");
  const pusat: LatLng = titik[0] ?? (desa.petaLat != null && desa.petaLng != null
    ? [Number(desa.petaLat), Number(desa.petaLng)]
    : DEFAULT_CENTER);

  return (
    <MapShell
      center={pusat}
      zoom={desa.wilayahZoom ?? 14}
      layerId="osm"
      className="h-[420px] rounded-xl"
    >
      {titik.length > 1 && <Sesuaikan titik={titik} />}
      {titik.length >= 3 && (
        <Polygon
          positions={titik}
          pathOptions={{ color: pinggir, fillColor: warna, fillOpacity: 0.3, weight: 2 }}
        />
      )}
      {titik.length === 2 && <Polyline positions={titik} pathOptions={{ color: pinggir }} />}
    </MapShell>
  );
}

export function PetaTitik({
  lat,
  lng,
  zoom = 16,
  label,
  warna,
  className = "h-[420px] rounded-xl",
}: {
  lat: number;
  lng: number;
  zoom?: number;
  label?: string;
  warna?: string | null;
  className?: string;
}) {
  const titik: LatLng = [lat, lng];
  return (
    <MapShell center={titik} zoom={zoom} layerId="osm" className={className}>
      <Recenter point={titik} zoom={zoom} />
      <Marker position={titik} icon={pointIcon(hex(warna, "#0f766e"))}>
        {label && (
          <Tooltip permanent direction="right" offset={[12, 0]}>
            {label}
          </Tooltip>
        )}
      </Marker>
    </MapShell>
  );
}

export function PetaLokasiKantor({ desa }: { desa: Desa }) {
  const lat = desa.petaLat == null ? null : Number(desa.petaLat);
  const lng = desa.petaLng == null ? null : Number(desa.petaLng);
  if (lat === null || lng === null || !Number.isFinite(lat) || !Number.isFinite(lng)) return null;

  return (
    <PetaTitik
      lat={lat}
      lng={lng}
      zoom={desa.petaZoom ?? 16}
      warna={desa.temaPrimer}
      label={desa.kantorDesa ?? `Kantor ${desa.nama}`}
    />
  );
}
