import { useEffect, useRef } from 'react';
import maplibregl from 'maplibre-gl';
import 'maplibre-gl/dist/maplibre-gl.css';

const MAP_STYLE = {
  version: 8 as const,
  sources: {
    osm: {
      type: 'raster' as const,
      tiles: ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'],
      tileSize: 256,
      attribution: '© OpenStreetMap',
    },
  },
  layers: [{ id: 'osm', type: 'raster' as const, source: 'osm' }],
};

// Guanare, Portuguesa (centro por defecto si el negocio aun no marco ubicacion).
const DEFAULT = { lat: 9.0451, lng: -69.748 };

export default function MapaUbicacion({
  lat,
  lng,
  onCambio,
}: {
  lat: number | null;
  lng: number | null;
  onCambio: (lat: number, lng: number) => void;
}) {
  const ref = useRef<HTMLDivElement | null>(null);
  const mapRef = useRef<maplibregl.Map | null>(null);
  const markerRef = useRef<maplibregl.Marker | null>(null);

  useEffect(() => {
    if (!ref.current || mapRef.current) return;
    const center = lat != null && lng != null ? { lat, lng } : DEFAULT;
    const map = new maplibregl.Map({
      container: ref.current,
      style: MAP_STYLE as maplibregl.StyleSpecification,
      center: [center.lng, center.lat],
      zoom: lat != null ? 16 : 13,
    });
    map.addControl(new maplibregl.NavigationControl({ showCompass: false }), 'top-right');
    mapRef.current = map;
    const marker = new maplibregl.Marker({ color: '#F97316', draggable: true })
      .setLngLat([center.lng, center.lat])
      .addTo(map);
    markerRef.current = marker;
    marker.on('dragend', () => {
      const p = marker.getLngLat();
      onCambio(p.lat, p.lng);
    });
    map.on('click', (e) => {
      marker.setLngLat(e.lngLat);
      onCambio(e.lngLat.lat, e.lngLat.lng);
    });
    return () => {
      map.remove();
      mapRef.current = null;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  function usarActual() {
    if (!('geolocation' in navigator)) {
      alert('Este dispositivo no tiene GPS.');
      return;
    }
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        const la = pos.coords.latitude;
        const ln = pos.coords.longitude;
        markerRef.current?.setLngLat([ln, la]);
        mapRef.current?.easeTo({ center: [ln, la], zoom: 16 });
        onCambio(la, ln);
      },
      (e) => alert('No se pudo obtener tu ubicacion: ' + e.message),
      { enableHighAccuracy: true, timeout: 10000 },
    );
  }

  return (
    <div>
      <div ref={ref} className="w-full h-56 rounded-xl overflow-hidden border border-white/10" />
      <div className="flex items-center justify-between mt-2">
        <button type="button" onClick={usarActual} className="text-sm font-semibold text-dorado">
          Usar mi ubicacion actual
        </button>
        <span className="text-xs text-niebla">
          {lat != null && lng != null ? `${lat.toFixed(5)}, ${lng.toFixed(5)}` : 'Toca el mapa para marcar'}
        </span>
      </div>
    </div>
  );
}
