import React, { useEffect, useRef, useState } from 'react';
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import { MapPin, Target } from 'lucide-react';

interface MapboxMapProps {
  initialLat?: number;
  initialLng?: number;
  onLocationChange?: (lat: number, lng: number) => void;
  height?: string;
}

export const MapboxMap: React.FC<MapboxMapProps> = ({
  initialLat = -23.5505, // São Paulo como padrão
  initialLng = -46.6333,
  onLocationChange,
  height = '400px'
}) => {
  const mapContainer = useRef<HTMLDivElement>(null);
  const map = useRef<mapboxgl.Map | null>(null);
  const marker = useRef<mapboxgl.Marker | null>(null);
  const [currentLat, setCurrentLat] = useState(initialLat);
  const [currentLng, setCurrentLng] = useState(initialLng);
  const [mapLoaded, setMapLoaded] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!mapContainer.current || map.current) return;

    try {
      console.log('🗺️ Inicializando mapa Mapbox...');
      // Configurar token
      const token = import.meta.env.VITE_MAPBOX_TOKEN;
      if (!token) {
        setError('❌ Token do Mapbox não encontrado. Configure VITE_MAPBOX_TOKEN no arquivo .env.local');
        return;
      }
      mapboxgl.accessToken = token;

      // Inicializar mapa
      map.current = new mapboxgl.Map({
        container: mapContainer.current,
        style: 'mapbox://styles/mapbox/streets-v12',
        center: [initialLng, initialLat],
        zoom: 15
      });

      console.log('✅ Mapa criado com sucesso');

      // Adicionar controles de navegação
      map.current.addControl(new mapboxgl.NavigationControl(), 'top-right');
      
      // Adicionar controle de localização
      map.current.addControl(
        new mapboxgl.GeolocateControl({
          positionOptions: {
            enableHighAccuracy: true
          },
          trackUserLocation: true,
          showUserHeading: true
        }),
        'top-right'
      );

      // Criar marcador arrastável
      marker.current = new mapboxgl.Marker({
        color: '#c5a059',
        draggable: true
      })
        .setLngLat([initialLng, initialLat])
        .addTo(map.current);

      // Evento quando o marcador é arrastado
      marker.current.on('dragend', () => {
        if (marker.current) {
          const lngLat = marker.current.getLngLat();
          setCurrentLat(lngLat.lat);
          setCurrentLng(lngLat.lng);
          if (onLocationChange) {
            onLocationChange(lngLat.lat, lngLat.lng);
          }
        }
      });

      // Evento de clique no mapa para mover o marcador
      map.current.on('click', (e) => {
        if (marker.current) {
          marker.current.setLngLat([e.lngLat.lng, e.lngLat.lat]);
          setCurrentLat(e.lngLat.lat);
          setCurrentLng(e.lngLat.lng);
          if (onLocationChange) {
            onLocationChange(e.lngLat.lat, e.lngLat.lng);
          }
        }
      });

      map.current.on('load', () => {
        setMapLoaded(true);
      });

    } catch (error: any) {
      console.error('Erro ao inicializar mapa:', error);
      const errorMsg = error?.message || String(error);
      if (errorMsg.includes('token') || errorMsg.includes('Unauthorized') || errorMsg.includes('401')) {
        setError('❌ Token do Mapbox inválido. Obtenha um token gratuito em https://account.mapbox.com/ e configure em services/mapboxService.ts');
      } else {
        setError(`Erro ao carregar o mapa: ${errorMsg}`);
      }
    }

    // Cleanup
    return () => {
      if (marker.current) {
        marker.current.remove();
      }
      if (map.current) {
        map.current.remove();
        map.current = null;
      }
    };
  }, []); // Executar apenas uma vez

  // Atualizar posição do marcador quando as coordenadas mudarem externamente
  useEffect(() => {
    if (marker.current && map.current && mapLoaded) {
      marker.current.setLngLat([initialLng, initialLat]);
      map.current.flyTo({
        center: [initialLng, initialLat],
        zoom: 15,
        duration: 1500
      });
      setCurrentLat(initialLat);
      setCurrentLng(initialLng);
    }
  }, [initialLat, initialLng, mapLoaded]);

  const centerOnMarker = () => {
    if (map.current && marker.current) {
      const lngLat = marker.current.getLngLat();
      map.current.flyTo({
        center: [lngLat.lng, lngLat.lat],
        zoom: 17,
        duration: 1000
      });
    }
  };

  return (
    <div className="relative">
      {error && (
        <div className="absolute top-0 left-0 right-0 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded z-10">
          {error}
        </div>
      )}
      
      <div 
        ref={mapContainer} 
        className="w-full rounded-lg border-2 border-gray-300 overflow-hidden shadow-md"
        style={{ height }}
      />
      
      {/* Info overlay - Responsivo */}
      <div className="absolute bottom-2 sm:bottom-4 left-2 sm:left-4 bg-white/95 backdrop-blur-sm px-2 py-2 sm:px-4 sm:py-3 rounded-lg shadow-lg border border-gray-200 max-w-[160px] sm:max-w-none">
        <div className="flex items-center space-x-2 sm:space-x-3">
          <MapPin size={16} className="text-brand-gold flex-shrink-0 hidden sm:block" />
          <div className="min-w-0">
            <p className="text-[10px] sm:text-xs text-gray-500 font-medium hidden sm:block">Coordenadas</p>
            <p className="text-[10px] sm:text-sm font-mono text-gray-800 truncate">
              {currentLat.toFixed(4)}, {currentLng.toFixed(4)}
            </p>
          </div>
        </div>
      </div>

      {/* Botão de centralizar - Responsivo */}
      <button
        onClick={centerOnMarker}
        className="absolute bottom-2 sm:bottom-4 right-2 sm:right-4 bg-white hover:bg-gray-50 p-2 sm:p-3 rounded-full shadow-lg border border-gray-200 transition-colors group"
        title="Centralizar no marcador"
      >
        <Target size={18} className="text-gray-600 group-hover:text-brand-gold transition-colors sm:w-5 sm:h-5" />
      </button>

      {/* Instruções - Responsivo */}
      <div className="mt-3 bg-blue-50 border border-blue-200 rounded-lg p-2 sm:p-3 text-xs sm:text-sm text-blue-800">
        <p className="font-medium mb-1 text-xs sm:text-sm">💡 Como usar:</p>
        <ul className="text-[11px] sm:text-xs space-y-0.5 sm:space-y-1 text-blue-700">
          <li className="flex items-start"><span className="mr-1">•</span><span><strong>Arraste o marcador</strong> para a posição exata</span></li>
          <li className="flex items-start"><span className="mr-1">•</span><span><strong>Clique no mapa</strong> para mover o marcador</span></li>
          <li className="flex items-start hidden sm:flex"><span className="mr-1">•</span><span>Use os <strong>controles</strong> para zoom e navegação</span></li>
        </ul>
      </div>
    </div>
  );
};
