import React, { useEffect, useRef, useState } from "react";
import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";
import { MapPin, Target, Lightbulb } 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>
      {error && (
        <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-3">
          {error}
        </div>
      )}

      <div className="relative">
        <div
          ref={mapContainer}
          className="w-full rounded-lg border-2 border-gray-300 overflow-hidden shadow-md"
          style={{ height }}
        />
      </div>

      {/* Info cards abaixo do mapa */}
      <div className="mt-3 grid grid-cols-1 sm:grid-cols-2 gap-3">
        {/* Card de Coordenadas */}
        <div className="bg-white rounded-lg shadow border border-gray-200 p-3">
          <div className="flex items-center space-x-2">
            <MapPin size={16} className="text-brand-gold flex-shrink-0" />
            <div className="min-w-0 flex-1">
              <p className="text-xs text-gray-500 font-medium">Coordenadas</p>
              <p className="text-sm font-mono text-gray-800 truncate">
                {currentLat.toFixed(4)}, {currentLng.toFixed(4)}
              </p>
            </div>
          </div>
        </div>

        {/* Card de Instruções */}
        <div className="bg-blue-50 rounded-lg shadow border border-blue-200 p-3">
          <p className="font-medium mb-1.5 text-xs text-blue-800 flex items-center gap-1.5"> 
             <Lightbulb className="w-4 h-4" /> Como usar: 
          </p>
          <ul className="text-xs space-y-1 text-blue-700">
            <li className="flex items-start">
              <span className="mr-1">•</span>
              <span>
                <strong>Arraste o marcador</strong> ou{" "}
                <strong>clique no mapa</strong>
              </span>
            </li>
            <li className="flex items-start">
              <span className="mr-1">•</span>
              <span>
                Use os <strong>controles</strong> para navegação
              </span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  );
};
