'use client';

import { useEffect, useRef } from 'react';

export default function AddPropertyMap({ mapCenter, mapZoom, selectedLocation, onMapClick, onMarkerDragEnd }) {
  const containerRef = useRef(null);
  const mapRef = useRef(null);
  const markerRef = useRef(null);
  const LRef = useRef(null);

  useEffect(() => {
    async function init() {
      const L = await import('leaflet');
      LRef.current = L;

      delete L.Icon.Default.prototype._getIconUrl;
      L.Icon.Default.mergeOptions({
        iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon-2x.png',
        iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon.png',
        shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
      });

      if (!containerRef.current || mapRef.current) return;

      const map = L.map(containerRef.current, {
        center: mapCenter,
        zoom: mapZoom,
        doubleClickZoom: false,
      });

      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; OpenStreetMap contributors',
      }).addTo(map);

      map.on('click', (e) => {
        const pos = [e.latlng.lat, e.latlng.lng];
        placeMarker(pos);
        map.setView(pos, mapZoom);
        onMapClick(pos);
      });

      mapRef.current = map;
      setTimeout(() => map.invalidateSize(), 200);
    }

    init();

    return () => {
      if (mapRef.current) {
        mapRef.current.remove();
        mapRef.current = null;
      }
    };
  }, []);

  function placeMarker(pos) {
    const L = LRef.current;
    if (!L || !mapRef.current) return;

    if (markerRef.current) {
      markerRef.current.setLatLng(pos);
    } else {
      markerRef.current = L.marker(pos, { draggable: true }).addTo(mapRef.current);
      markerRef.current.on('dragend', (ev) => {
        const p = ev.target.getLatLng();
        onMarkerDragEnd(p.lat, p.lng);
      });
    }
  }

  useEffect(() => {
    const map = mapRef.current;
    if (!map) return;
    map.setView(mapCenter, mapZoom);
  }, [mapCenter, mapZoom]);

  useEffect(() => {
    if (!selectedLocation || !mapRef.current) return;
    const pos = [selectedLocation.lat, selectedLocation.lng];
    mapRef.current.setView(pos, mapZoom);
    placeMarker(pos);
  }, [selectedLocation]);

  return <div ref={containerRef} className="w-full h-full z-0" />;
}
