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

// Fix for default markers in Leaflet with Vite
delete (L.Icon.Default.prototype as any)._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon-2x.png',
  iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png',
});

export interface MapMarker {
  id: string;
  lat: number;
  lng: number;
  title: string;
  type: 'client' | 'pharmacy' | 'courier' | 'destination' | 'pickup';
  status?: string;
  info?: string;
  address?: string;
  distance?: number;
  duration?: number;
  isActive?: boolean;
  onClick?: () => void;
}

interface MapProps {
  center: [number, number];
  zoom?: number;
  markers?: MapMarker[];
  onMapClick?: (lat: number, lng: number) => void;
  showUserLocation?: boolean;
  height?: string;
  className?: string;
  interactive?: boolean;
  showRoutes?: boolean;
  realTimeTracking?: boolean;
  onLocationSelect?: (lat: number, lng: number, address?: string) => void;
}

const markerIcons = {
  client: '👤',
  pharmacy: '⚕️', 
  courier: '🚴',
  destination: '📍',
  pickup: '📦'
};

const markerColors = {
  client: '#3b82f6',
  pharmacy: '#10b981', 
  courier: '#f59e0b',
  destination: '#ef4444',
  pickup: '#8b5cf6'
};

export function Map({ 
  center, 
  zoom = 13, 
  markers = [], 
  onMapClick,
  showUserLocation = false,
  height = '400px',
  className = '',
  interactive = true,
  showRoutes = false,
  realTimeTracking = false,
  onLocationSelect
}: MapProps) {
  // Ensure center is valid
  if (!center || center.length !== 2) {
    center = [5.3364, -4.0267]; // Default Abidjan center
  }
  const mapRef = useRef<HTMLDivElement>(null);
  const mapInstanceRef = useRef<L.Map | null>(null);
  const markersRef = useRef<L.Marker[]>([]);

  useEffect(() => {
    if (!mapRef.current || mapInstanceRef.current) return;

    // Initialize map
    const map = L.map(mapRef.current, {
      scrollWheelZoom: interactive,
      doubleClickZoom: interactive,
      dragging: interactive,
      zoomControl: interactive,
      touchZoom: interactive,
      boxZoom: interactive,
      keyboard: interactive
    }).setView(center, zoom);

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

    // Add click handler
    if (onMapClick && interactive) {
      map.on('click', (e) => {
        onMapClick(e.latlng.lat, e.latlng.lng);
      });
    }

    mapInstanceRef.current = map;

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

  // Update map center when props change
  useEffect(() => {
    if (mapInstanceRef.current && center && center.length === 2) {
      mapInstanceRef.current.setView(center, zoom);
    }
  }, [center, zoom]);

  // Update markers
  useEffect(() => {
    if (!mapInstanceRef.current) return;

    // Clear existing markers
    markersRef.current.forEach(marker => {
      mapInstanceRef.current?.removeLayer(marker);
    });
    markersRef.current = [];

    // Add new markers - validate marker data first
    markers.filter(markerData => markerData && typeof markerData.lat === 'number' && typeof markerData.lng === 'number').forEach(markerData => {
      const isActiveMarker = markerData.isActive || markerData.type === 'courier';
      const size = isActiveMarker ? 40 : 32;
      
      const icon = L.divIcon({
        html: `
          <div style="
            background-color: ${markerColors[markerData.type]};
            width: ${size}px;
            height: ${size}px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: ${size/2}px;
            border: 3px solid white;
            box-shadow: 0 2px 8px rgba(0,0,0,0.3);
            ${isActiveMarker ? 'animation: markerPulse 2s infinite;' : ''}
            position: relative;
            z-index: ${isActiveMarker ? 1000 : 100};
          ">
            ${markerIcons[markerData.type]}
          </div>
          <style>
            @keyframes markerPulse {
              0% { transform: scale(1); box-shadow: 0 2px 8px rgba(0,0,0,0.3); }
              50% { transform: scale(1.1); box-shadow: 0 4px 16px rgba(0,0,0,0.4); }
              100% { transform: scale(1); box-shadow: 0 2px 8px rgba(0,0,0,0.3); }
            }
          </style>
        `,
        className: 'custom-marker',
        iconSize: [size, size],
        iconAnchor: [size/2, size/2],
        popupAnchor: [0, -size/2]
      });

      const marker = L.marker([markerData.lat, markerData.lng], { icon })
        .addTo(mapInstanceRef.current!);

      // Enhanced popup with more information
      const popupContent = `
        <div style="min-width: 200px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
          <h4 style="margin: 0 0 12px 0; color: ${markerColors[markerData.type]}; font-size: 16px; font-weight: bold;">
            ${markerIcons[markerData.type]} ${markerData.title}
          </h4>
          ${markerData.status ? `
            <div style="margin: 8px 0; padding: 4px 8px; background: #f3f4f6; border-radius: 4px; font-size: 12px; font-weight: bold; color: #374151;">
              Statut: ${markerData.status}
            </div>
          ` : ''}
          ${markerData.info ? `<p style="margin: 8px 0; font-size: 14px; color: #6b7280;">${markerData.info}</p>` : ''}
          ${markerData.address ? `
            <p style="margin: 8px 0; font-size: 12px; color: #6b7280;">
              📍 ${markerData.address}
            </p>
          ` : ''}
          ${markerData.distance ? `
            <p style="margin: 8px 0; font-size: 12px; color: #3b82f6; font-weight: bold;">
              📏 Distance: ${markerData.distance.toFixed(1)} km
            </p>
          ` : ''}
          ${markerData.duration ? `
            <p style="margin: 8px 0; font-size: 12px; color: #10b981; font-weight: bold;">
              ⏱️ Temps estimé: ${markerData.duration} min
            </p>
          ` : ''}
          <p style="margin: 8px 0 0 0; font-size: 10px; color: #9ca3af; border-top: 1px solid #e5e7eb; padding-top: 4px;">
            ${markerData.lat.toFixed(6)}, ${markerData.lng.toFixed(6)}
          </p>
        </div>
      `;

      marker.bindPopup(popupContent, {
        maxWidth: 300,
        className: 'custom-popup'
      });

      // Add click handler
      if (markerData.onClick) {
        marker.on('click', markerData.onClick);
      }

      markersRef.current.push(marker);
    });

    // Fit bounds if multiple markers
    if (markers.length > 1 && markersRef.current.length > 1) {
      const group = new (L as any).FeatureGroup(markersRef.current);
      mapInstanceRef.current.fitBounds(group.getBounds().pad(0.1));
    }
  }, [markers]);

  // Add user location if requested
  useEffect(() => {
    if (showUserLocation && mapInstanceRef.current) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const { latitude, longitude } = position.coords;
          
          const userIcon = L.divIcon({
            html: `
              <div style="
                background-color: #3b82f6;
                width: 20px;
                height: 20px;
                border-radius: 50%;
                border: 3px solid white;
                box-shadow: 0 2px 4px rgba(0,0,0,0.3);
              "></div>
            `,
            className: '',
            iconSize: [20, 20],
            iconAnchor: [10, 10]
          });

          L.marker([latitude, longitude], { icon: userIcon })
            .addTo(mapInstanceRef.current!)
            .bindPopup('Votre position actuelle');
        },
        (error) => {
          console.warn('Géolocalisation non disponible:', error);
        }
      );
    }
  }, [showUserLocation]);

  return (
    <div 
      ref={mapRef} 
      style={{ height, width: '100%' }}
      className={`rounded-lg overflow-hidden border ${className}`}
      data-testid="map-container"
    />
  );
}