'use client';

import React, { useEffect, useRef } from 'react';
import L from 'leaflet';

interface LocationPickerMapProps {
  lat: number;
  lng: number;
  accuracy?: number | null;
  mapMode?: 'm' | 'y';
  onChangeLocation: (lat: number, lng: number) => void;
}

export default function LocationPickerMap({
  lat,
  lng,
  accuracy = null,
  mapMode = 'y',
  onChangeLocation,
}: LocationPickerMapProps) {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const mapRef = useRef<L.Map | null>(null);
  const markerRef = useRef<L.Marker | null>(null);
  const circleRef = useRef<L.Circle | null>(null);
  const tileRef = useRef<L.TileLayer | null>(null);
  const onChangeRef = useRef(onChangeLocation);

  onChangeRef.current = onChangeLocation;

  useEffect(() => {
    if (!containerRef.current || mapRef.current) return;

    const map = L.map(containerRef.current, {
      center: [lat, lng],
      zoom: 16,
      zoomControl: true,
    });

    const tile = L.tileLayer(`https://mt1.google.com/vt/lyrs=${mapMode}&x={x}&y={y}&z={z}`, {
      maxZoom: 20,
      attribution: '&copy; Google Maps',
    }).addTo(map);

    const pinIcon = L.divIcon({
      className: '',
      html: `<div class="hazard-marker-pulse" style="width:30px;height:30px;border-radius:999px;background:#dc2626;border:3px solid #ffffff;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 12px rgba(0,0,0,0.65);cursor:grab;">
        <div style="width:8px;height:8px;border-radius:999px;background:#ffffff;"></div>
      </div>`,
      iconSize: [30, 30],
      iconAnchor: [15, 15],
    });

    const marker = L.marker([lat, lng], {
      icon: pinIcon,
      draggable: true,
    }).addTo(map);

    marker.on('dragend', () => {
      const pos = marker.getLatLng();
      onChangeRef.current(Number(pos.lat.toFixed(6)), Number(pos.lng.toFixed(6)));
    });

    map.on('click', (e: L.LeafletMouseEvent) => {
      const nextLat = Number(e.latlng.lat.toFixed(6));
      const nextLng = Number(e.latlng.lng.toFixed(6));
      marker.setLatLng([nextLat, nextLng]);
      onChangeRef.current(nextLat, nextLng);
    });

    mapRef.current = map;
    markerRef.current = marker;
    tileRef.current = tile;

    return () => {
      map.remove();
      mapRef.current = null;
      markerRef.current = null;
      circleRef.current = null;
      tileRef.current = null;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    if (!tileRef.current) return;
    tileRef.current.setUrl(`https://mt1.google.com/vt/lyrs=${mapMode}&x={x}&y={y}&z={z}`);
  }, [mapMode]);

  useEffect(() => {
    if (!mapRef.current || !markerRef.current) return;
    markerRef.current.setLatLng([lat, lng]);
    mapRef.current.panTo([lat, lng], { animate: true });

    if (circleRef.current) {
      circleRef.current.remove();
      circleRef.current = null;
    }
    if (accuracy && accuracy > 0 && accuracy <= 2000) {
      circleRef.current = L.circle([lat, lng], {
        radius: accuracy,
        color: accuracy <= 50 ? '#10b981' : '#f59e0b',
        fillColor: accuracy <= 50 ? '#10b981' : '#f59e0b',
        fillOpacity: 0.12,
        weight: 1.5,
      }).addTo(mapRef.current);
    }
  }, [lat, lng, accuracy]);

  return (
    <div className="w-full h-[210px] rounded-xl overflow-hidden border border-zinc-700 bg-zinc-950 relative">
      <div ref={containerRef} className="w-full h-full z-0" />
    </div>
  );
}
