import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import 'leaflet.markercluster/dist/MarkerCluster.css';
import 'leaflet.markercluster/dist/MarkerCluster.Default.css';
import 'leaflet.markercluster';
import { useEffect, useRef } from 'react';
import { POI, useRouteStore } from '@/store/route-store';
import { Place } from '@/utils/route-optimizer';
import { getPOIById } from '@/services/poi-service';
import { useToast } from '@/hooks/use-toast';

const MAPTILER_API_KEY = import.meta.env.VITE_MAPTILER_API_KEY;

export function MapTilerMap({ places, allPOIs, onPlaceClick }: { places: Place[]; allPOIs: POI[]; onPlaceClick?: (place: any) => void }) {
  const { toast } = useToast();
  const mapContainer = useRef<HTMLDivElement>(null);
  const map = useRef<L.Map | null>(null);
  const markersRef = useRef<L.Marker[]>([]);
  const clusterGroup = useRef<L.MarkerClusterGroup | null>(null);
  const polylineRef = useRef<L.Polyline | null>(null);

  useEffect(() => {
    (window as any).addPOIToRoute = async (poiId: string) => {
      try {
        const poi = await getPOIById(poiId);
        if (poi) {
          useRouteStore.getState().addPlaceToRoute(poi as any);
          toast({
            title: 'Başarılı',
            description: `${poi.name} rotaya eklendi`,
          });
        }
      } catch (error) {
        toast({
          title: 'Hata',
          description: 'Yer rotaya eklenirken hata oluştu',
          variant: 'destructive'
        });
      }
    };

    (window as any).removePlaceFromRoute = (placeId: string) => {
      const place = useRouteStore.getState().selectedPlaces.find(p => p.id === placeId);
      if (place && confirm(`${place.name} rotadan çıkarılsın mı?`)) {
        useRouteStore.getState().removePlaceFromRoute(placeId);
        toast({
          title: 'Başarılı',
          description: `${place.name} rotadan çıkarıldı`,
        });
      }
    };
  }, [toast]);

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

    map.current = L.map(mapContainer.current, {
      center: [38.6431, 34.8289],
      zoom: 11,
      zoomControl: true,
      attributionControl: true
    });

    L.tileLayer(
      `https://api.maptiler.com/maps/outdoor-v2/{z}/{x}/{y}.png?key=${MAPTILER_API_KEY}`,
      {
        attribution: '© <a href="https://www.maptiler.com/">MapTiler</a> © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
        maxZoom: 19,
        tileSize: 512,
        zoomOffset: -1
      }
    ).addTo(map.current);

    clusterGroup.current = L.markerClusterGroup({
      maxClusterRadius: 50,
      spiderfyOnMaxZoom: true,
      showCoverageOnHover: false,
      zoomToBoundsOnClick: true,
      iconCreateFunction: (cluster) => {
        const count = cluster.getChildCount();
        return L.divIcon({
          html: `<div style="background-color: rgba(79, 70, 229, 0.8); width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; border: 3px solid white; box-shadow: 0 2px 8px rgba(0,0,0,0.3);">${count}</div>`,
          className: 'marker-cluster-custom',
          iconSize: L.point(40, 40)
        });
      }
    });

    map.current.addLayer(clusterGroup.current);

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

  const getCategoryIcon = (category: string): L.DivIcon => {
    const iconConfig: Record<string, { color: string; icon: string }> = {
      'restaurant': { color: '#FF6347', icon: '🍽️' },
      'attraction': { color: '#4169E1', icon: '🏛️' },
      'hotel': { color: '#9370DB', icon: '🏨' },
      'activity': { color: '#FF8C00', icon: '🎈' },
      'nature': { color: '#228B22', icon: '🌳' },
      'shopping': { color: '#DC143C', icon: '🛍️' },
      'default': { color: '#808080', icon: '📍' }
    };

    const config = iconConfig[category.toLowerCase()] || iconConfig.default;

    return L.divIcon({
      className: 'poi-marker',
      html: `<div style="background-color: ${config.color}; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-size: 16px; border: 2px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.3); cursor: pointer;">${config.icon}</div>`,
      iconSize: [32, 32],
      iconAnchor: [16, 16]
    });
  };

  const displayAllPOIs = () => {
    if (!map.current || !clusterGroup.current) return;

    clusterGroup.current.clearLayers();

    allPOIs.forEach((poi) => {
      const marker = L.marker([poi.latitude, poi.longitude], {
        icon: getCategoryIcon(poi.category)
      });

      marker.bindPopup(`
        <div style="min-width: 250px; max-width: 300px;">
          ${poi.imageUrl ? `<img src="${poi.imageUrl}" alt="${poi.name}" style="width: 100%; height: 150px; object-fit: cover; border-radius: 8px; margin-bottom: 8px;" />` : ''}
          <h3 style="margin: 0 0 8px 0; font-size: 16px; font-weight: bold;">${poi.name}</h3>
          <p style="margin: 0 0 4px 0; font-size: 12px; color: #666;">${poi.category}</p>
          ${poi.rating ? `<p style="margin: 0 0 8px 0; font-size: 12px; color: #FFD700;">⭐ ${poi.rating}/5</p>` : ''}
          <p style="margin: 0 0 12px 0; font-size: 13px; line-height: 1.4;">${poi.description || ''}</p>
          <button onclick="addPOIToRoute('${poi.id}')" style="width: 100%; padding: 8px 16px; background-color: #4F46E5; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 500; transition: background-color 0.2s;">Rotaya Ekle</button>
        </div>
      `, {
        maxWidth: 300,
        className: 'custom-popup'
      });

      clusterGroup.current!.addLayer(marker);
    });
  };

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

    markersRef.current.forEach(marker => marker.remove());
    markersRef.current = [];

    if (polylineRef.current) {
      polylineRef.current.remove();
    }

    places.forEach((place, index) => {
      const customIcon = L.divIcon({
        className: 'route-marker',
        html: `<div style="background-color: #4F46E5; width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 16px; border: 3px solid white; box-shadow: 0 3px 10px rgba(0,0,0,0.4); cursor: pointer; z-index: 1000;">${index + 1}</div>`,
        iconSize: [40, 40],
        iconAnchor: [20, 20]
      });

      const marker = L.marker([place.latitude, place.longitude], {
        icon: customIcon,
        zIndexOffset: 1000
      }).addTo(map.current!);

      marker.bindPopup(`
        <div style="min-width: 250px;">
          ${place.imageUrl ? `<img src="${place.imageUrl}" alt="${place.name}" style="width: 100%; height: 150px; object-fit: cover; border-radius: 8px; margin-bottom: 8px;" />` : ''}
          <h3 style="margin: 0 0 8px 0; font-size: 16px; font-weight: bold;">${place.name}</h3>
          <p style="margin: 0 0 8px 0; font-size: 13px; line-height: 1.4;">${place.description}</p>
          <p style="margin: 0 0 12px 0; font-size: 12px; color: #666;">Sıra: ${index + 1}</p>
          <button onclick="removePlaceFromRoute('${place.id}')" style="width: 100%; padding: 8px 16px; background-color: #EF4444; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 500;">Rotadan Çıkar</button>
        </div>
      `, {
        maxWidth: 300
      });

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

    if (places.length >= 2) {
      const latLngs: L.LatLngExpression[] = places.map(p => [p.latitude, p.longitude]);
      polylineRef.current = L.polyline(latLngs, {
        color: '#4F46E5',
        weight: 4,
        opacity: 0.7,
        smoothFactor: 1
      }).addTo(map.current!);

      map.current!.fitBounds(polylineRef.current.getBounds(), {
        padding: [50, 50]
      });
    }
  };

  useEffect(() => {
    if (!map.current) return;
    updateRouteAndMarkers();
  }, [places]);

  useEffect(() => {
    if (!map.current || !clusterGroup.current) return;
    displayAllPOIs();
  }, [allPOIs]);

  return (
    <div
      ref={mapContainer}
      style={{ width: '100%', height: '100%' }}
      className="maptiler-map"
    />
  );
}
