import { useEffect, useRef } from 'react';
import { useProjectStats, useProjectLocations } from '../../hooks/useProjectData';

interface ColombiaMapProps {
  className?: string;
}

interface GoogleMapsAPI {
  maps: {
    Map: new (element: HTMLElement, options: unknown) => GoogleMap;
    Marker: new (options: unknown) => GoogleMarker;
    SymbolPath: {
      CIRCLE: unknown;
    };
    Animation: {
      DROP: unknown;
      BOUNCE: unknown;
    };
    LatLngBounds: new () => GoogleLatLngBounds;
  };
}

interface GoogleMap {
  data: {
    loadGeoJson: (url: string) => void;
    setStyle: (style: unknown) => void;
    addListener: (event: string, callback: (event: GoogleDataFeatureEvent) => void) => void;
  };
  fitBounds: (bounds: GoogleLatLngBounds) => void;
  [key: string]: unknown;
}

interface GoogleMarker {
  setAnimation: (animation: unknown) => void;
}

interface GoogleLatLngBounds {
  extend: (latlng: GoogleLatLng) => void;
}

interface GoogleLatLng {
  lat: () => number;
  lng: () => number;
}

interface GoogleDataFeatureEvent {
  feature: {
    getGeometry: () => {
      forEachLatLng: (callback: (latlng: GoogleLatLng) => void) => void;
    };
  };
}

declare global {
  interface Window {
    google: GoogleMapsAPI;
    initColombiaMap: () => void;
  }
}

export default function ColombiaMap({ className = '' }: ColombiaMapProps) {
  const mapRef = useRef<HTMLDivElement>(null);
  const mapInstanceRef = useRef<GoogleMap | null>(null);
  const { stats: projectStats } = useProjectStats();
  const { locations: projectLocations } = useProjectLocations();

  useEffect(() => {
    const apiKey = import.meta.env.VITE_GOOGLE_MAPS_API_KEY;

    if (!apiKey) {
      // console.warn('Google Maps API key not found');
      return;
    }

    const initializeMap = () => {
      if (!mapRef.current || !window.google) return;

      // Custom style inspired by green theme
      const mapStyles: Array<{
        featureType?: string;
        elementType?: string;
        stylers: Array<{ [key: string]: string | number }>;
      }> = [
        // {
        //   "featureType": "all",
        //   "elementType": "geometry",
        //   "stylers": [
        //     {
        //       "color": "#ffffff"
        //     }
        //   ]
        // },
        // {
        //   "featureType": "all",
        //   "elementType": "labels.text.fill",
        //   "stylers": [
        //     {
        //       "gamma": 0.01
        //     },
        //     {
        //       "lightness": 20
        //     },
        //     {
        //       "color": "#10b981"
        //     }
        //   ]
        // },
        // {
        //   "featureType": "all",
        //   "elementType": "labels.text.stroke",
        //   "stylers": [
        //     {
        //       "saturation": -31
        //     },
        //     {
        //       "lightness": -33
        //     },
        //     {
        //       "weight": 2
        //     },
        //     {
        //       "gamma": 0.8
        //     },
        //     {
        //       "color": "#ffffff"
        //     }
        //   ]
        // },
        // {
        //   "featureType": "administrative",
        //   "elementType": "labels.text.fill",
        //   "stylers": [
        //     {
        //       "color": "#047857"
        //     }
        //   ]
        // },
        // {
        //   "featureType": "landscape",
        //   "elementType": "geometry",
        //   "stylers": [
        //     {
        //       "lightness": 30
        //     },
        //     {
        //       "saturation": 30
        //     },
        //     {
        //       "color": "#f0fdf4"
        //     }
        //   ]
        // },
        // {
        //   "featureType": "poi",
        //   "elementType": "geometry",
        //   "stylers": [
        //     {
        //       "saturation": 20
        //     },
        //     {
        //       "color": "#dcfce7"
        //     }
        //   ]
        // },
        // {
        //   "featureType": "poi.park",
        //   "elementType": "geometry",
        //   "stylers": [
        //     {
        //       "lightness": 20
        //     },
        //     {
        //       "saturation": -20
        //     },
        //     {
        //       "color": "#86efac"
        //     }
        //   ]
        // },
        // {
        //   "featureType": "road",
        //   "elementType": "geometry",
        //   "stylers": [
        //     {
        //       "lightness": 10
        //     },
        //     {
        //       "saturation": -30
        //     },
        //     {
        //       "color": "#ffffff"
        //     }
        //   ]
        // },
        // {
        //   "featureType": "road",
        //   "elementType": "geometry.stroke",
        //   "stylers": [
        //     {
        //       "saturation": 25
        //     },
        //     {
        //       "lightness": 25
        //     },
        //     {
        //       "color": "#d1fae5"
        //     }
        //   ]
        // },
        // {
        //   "featureType": "water",
        //   "elementType": "all",
        //   "stylers": [
        //     {
        //       "lightness": -20
        //     },
        //     {
        //       "color": "#a7f3d0"
        //     }
        //   ]
        // }
      ];

      const map = new window.google.maps.Map(mapRef.current, {
        zoom: 9.4,
        center: { lat: 8.75111426934212, lng: -75.88054604758426 }, // Centro de Colombia
        styles: mapStyles,
        mapTypeId: "terrain",
        disableDefaultUI: true,
        zoomControl: false,
        mapTypeControl: false,
        scaleControl: false,
        streetViewControl: false,
        rotateControl: false,
        fullscreenControl: false,
        gestureHandling: 'none', // Disable interactions for demo
      });

      mapInstanceRef.current = map;

      // Cargar el archivo GeoJSON para resaltar Córdoba
      map.data.loadGeoJson('/assets/json/cordoba.geojson');

      // Estilo del polígono de Córdoba con resaltado de Montería
      map.data.setStyle(function(feature: any) {
        const nombre = feature.getProperty('NOMBRE_ENT');
        if (nombre === 'MONTERÍA') {
          return {
            fillColor: "#0066FF",
            fillOpacity: 0.2,
            strokeColor: "#003399",
            strokeWeight: 1.2,
          };
        } else {
          return {
            fillColor: "#0066FF",
            fillOpacity: 0.1,
            strokeColor: "#003399",
            strokeWeight: 0.4,
          };
        }
      });

      // Use real project locations if available, fallback to sample data
      const locationsToUse = projectLocations.length > 0 ? projectLocations : [
        { lat: 4.7110, lng: -74.0721, title: "Proyecto Bogotá - Innovación Pedagógica" },
        { lat: 6.2442, lng: -75.5812, title: "Proyecto Medellín - Metodologías Activas" },
        { lat: 3.4516, lng: -76.5320, title: "Proyecto Cali - Educación Digital" },
        { lat: 7.8939, lng: -72.5078, title: "Proyecto Cúcuta - Collaborative Learning" },
        { lat: 10.9685, lng: -74.7813, title: "Proyecto Barranquilla - STEAM Education" },
      ];

      locationsToUse.forEach((location, index) => {
        const marker = new window.google.maps.Marker({
          position: { lat: location.lat, lng: location.lng },
          map: map,
          title: location.title,
          icon: {
            path: window.google.maps.SymbolPath.CIRCLE,
            scale: 8,
            fillColor: index % 2 === 0 ? '#10b981' : '#059669',
            fillOpacity: 0.9,
            strokeColor: '#ffffff',
            strokeWeight: 2,
          },
          animation: window.google.maps.Animation.DROP,
        });

        // Add a subtle bounce animation
        setTimeout(() => {
          marker.setAnimation(window.google.maps.Animation.BOUNCE);
          setTimeout(() => {
            marker.setAnimation(null);
          }, 1400);
        }, index * 200);
      });
    };

    // Use a stable global callback and queue similar to interactive-map
    const GLOBAL_INIT_FN = 'initInteractiveMap';
    const queueKey = '__interactiveMapReadyQueue';
    if (!(window as any)[queueKey]) {
      (window as any)[queueKey] = [] as Array<() => void>;
    }

    if (!(window as any)[GLOBAL_INIT_FN]) {
      (window as any)[GLOBAL_INIT_FN] = () => {
        const q = (window as any)[queueKey] as Array<() => void>;
        while (q && q.length) {
          const fn = q.shift();
          if (typeof fn === 'function') {
            try { fn(); } catch (err) { console.error('Error running queued map initializer', err); }
          }
        }
      };
    }

    const initializerWrapper = () => {
      requestAnimationFrame(() => {
        setTimeout(initializeMap, 50);
      });
    };

    const loadGoogleMaps = () => {
      if (window.google) {
        initializerWrapper();
        return;
      }

      const existingScript = document.querySelector(`script[src*="maps.googleapis.com"]`);
      if (existingScript) {
        // console.log('Google Maps script already loading...');
        if (window.google) {
          initializerWrapper();
          return;
        }

        try {
          const src = (existingScript as HTMLScriptElement).src || '';
          const hasOurCallback = src.includes(`callback=${GLOBAL_INIT_FN}`) || src.includes(`callback=${GLOBAL_INIT_FN}&`);
          const isMarked = (existingScript as HTMLScriptElement).getAttribute('data-interactive-maps') === '1';

          if (!hasOurCallback && !isMarked) {
            const script = document.createElement('script');
            script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&callback=${GLOBAL_INIT_FN}`;
            script.async = true;
            script.defer = true;
            script.setAttribute('data-interactive-maps', '1');
            document.head.appendChild(script);

            script.onerror = () => {
              // console.error('Failed to load Google Maps API');
            };
            script.onload = () => {
              if (window.google && typeof (window as any)[GLOBAL_INIT_FN] === 'function') {
                try { (window as any)[GLOBAL_INIT_FN](); } catch (err) { /* ignore */ }
              }
            };
            (window as any)[queueKey].push(initializerWrapper);
            return;
          }
        } catch (err) {
          // ignore and continue to queue
        }

        (window as any)[queueKey].push(initializerWrapper);
        return;
      }

      const script = document.createElement('script');
      script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&callback=${GLOBAL_INIT_FN}`;
      script.async = true;
      script.defer = true;
      document.head.appendChild(script);

      script.onerror = () => {
        // console.error('Failed to load Google Maps API');
      };

      script.onload = () => {
        if (window.google && typeof (window as any)[GLOBAL_INIT_FN] === 'function') {
          try { (window as any)[GLOBAL_INIT_FN](); } catch (err) { /* ignore */ }
        }
      };
    };

    loadGoogleMaps();

    // Cleanup
    return () => {
      try {
        const q = (window as any)[queueKey] as Array<() => void> | undefined;
        if (q && q.length) {
          const idx = q.indexOf(initializerWrapper as unknown as () => void);
          if (idx !== -1) q.splice(idx, 1);
        }
      } catch (err) { /* ignore */ }
    };
  }, [projectLocations]);

  return (
    <div className={`relative ${className}`}>
      <div
        ref={mapRef}
        className="w-full h-full rounded-2xl overflow-hidden shadow-2xl border border-emerald-200 dark:border-emerald-400/30"
        style={{ minHeight: '300px' }}
      />

      {/* Overlay with project information */}
      <div className="absolute top-4 left-4 bg-white/95 dark:bg-slate-800/95 backdrop-blur-sm rounded-xl p-3 shadow-lg border border-emerald-200 dark:border-emerald-400/50">
        <div className="text-emerald-700 dark:text-emerald-400 text-xs font-semibold">Colombia</div>
        <div className="text-slate-800 dark:text-white text-lg font-bold">{projectStats.total_projects}</div>
        <div className="text-slate-600 dark:text-slate-300 text-xs">Proyectos MIRATE</div>
      </div>

      <div className="absolute top-4 right-4 bg-white/95 dark:bg-slate-800/95 backdrop-blur-sm rounded-xl p-3 shadow-lg border border-emerald-200 dark:border-emerald-400/50">
        <div className="text-emerald-700 dark:text-emerald-400 text-xs font-semibold">Cobertura</div>
        <div className="text-slate-800 dark:text-white text-lg font-bold">{projectStats.cities}</div>
        <div className="text-slate-600 dark:text-slate-300 text-xs">Ciudades</div>
      </div>

      <div className="absolute bottom-4 left-4 bg-white/95 dark:bg-slate-800/95 backdrop-blur-sm rounded-xl p-3 shadow-lg border border-emerald-200 dark:border-emerald-400/50">
        <div className="text-emerald-700 dark:text-emerald-400 text-xs font-semibold">Metodologías</div>
        <div className="text-slate-800 dark:text-white text-lg font-bold">CC</div>
        <div className="text-slate-600 dark:text-slate-300 text-xs">Activas</div>
      </div>
    </div>
  );
}
