import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import React, { useEffect, useRef } from 'react';

export interface PlaceData {
  id: string;
  lat: number;
  lng: number;
  title: string;
  description?: string;
}

export interface LeafletMapProps {
  places?: PlaceData[];
  className?: string;
  onMarkerClick?: (placeId: string) => void;
  onMarkerHover?: (placeId: string | null) => void;
  hoveredPlaceId?: string | null;
  selectedPlaceId?: string | null;
  activeDayId?: string | null;
  showPolyline?: boolean;
  center?: { lat: number; lng: number };
}

const LeafletMapDirect: React.FC<LeafletMapProps> = ({
  places = [],
  className = "w-full h-full",
  onMarkerClick,
  onMarkerHover,
  hoveredPlaceId,
  selectedPlaceId,
  showPolyline = false,
  center
}) => {
  const mapContainer = useRef<HTMLDivElement>(null);
  const map = useRef<L.Map | null>(null);
  const markersRef = useRef<Map<string, L.Marker>>(new Map());
  const polylineRef = useRef<L.Polyline | null>(null);

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

    const mapCenter: L.LatLngExpression = center ? [center.lat, center.lng] : [38.6431, 34.8289];
    
    map.current = L.map(mapContainer.current, {
      center: mapCenter,
      zoom: 11,
      zoomControl: true,
      attributionControl: true
    });

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

    return () => {
      map.current?.remove();
      map.current = null;
    };
  }, []);

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

    // Clear old markers
    markersRef.current.forEach(marker => marker.remove());
    markersRef.current.clear();
    if (polylineRef.current) polylineRef.current.remove();

    if (places.length === 0) return;

    const latLngs: L.LatLngExpression[] = [];

    places.forEach((place, index) => {
      const marker = L.marker([place.lat, place.lng], {
        title: place.title,
      })
      .addTo(map.current!)
      .on('click', () => onMarkerClick?.(place.id))
      .on('mouseover', () => onMarkerHover?.(place.id))
      .on('mouseout', () => onMarkerHover?.(null));

      if (place.description) {
        marker.bindPopup(`<b>${place.title}</b><br/>${place.description}`);
      }

      markersRef.current.set(place.id, marker);
      latLngs.push([place.lat, place.lng]);
    });

    if (showPolyline && latLngs.length >= 2) {
      polylineRef.current = L.polyline(latLngs, {
        color: '#4F46E5',
        weight: 3,
        opacity: 0.7
      }).addTo(map.current!);
    }

    // Auto fit bounds
    if (latLngs.length > 0) {
      const bounds = L.latLngBounds(latLngs);
      map.current.fitBounds(bounds, { padding: [30, 30], maxZoom: 14 });
    }
  }, [places, showPolyline, center]);

  useEffect(() => {
    if (!map.current) return;
    
    // Highlight selected/hovered markers
    markersRef.current.forEach((marker, id) => {
      const el = marker.getElement();
      if (el) {
        if (id === selectedPlaceId) {
          el.style.filter = "hue-rotate(180deg) scale(1.2)";
          el.style.zIndex = "1000";
        } else if (id === hoveredPlaceId) {
          el.style.filter = "hue-rotate(90deg) scale(1.1)";
          el.style.zIndex = "999";
        } else {
          el.style.filter = "";
          el.style.zIndex = "";
        }
      }
    });
  }, [selectedPlaceId, hoveredPlaceId]);

  return <div ref={mapContainer} className={className} style={{ minHeight: '400px' }} />;
};

export default LeafletMapDirect;
