'use client';

import { useState, useCallback, useRef, useEffect, useMemo } from 'react';
import { Box, type SxProps, type Theme } from '@mui/material';
import { MyLocation as MyLocationIcon } from '@mui/icons-material';
import { GoogleMap, useJsApiLoader, Marker, InfoWindow } from '@react-google-maps/api';
import { CircuitMap, RouteMarker, MarkerType, MapType } from '@/shared/types/Maps';
import MapMarker from './map-marker';

import { MapPolyline } from './map-polyline';
import ConditionalComponent from '../table/ConditionalComponent';
const DEFAULT_CENTER = {
  lat: 43.2965,
  lng: 5.3798,
};

const DEFAULT_ZOOM = 18;
const GOOGLE_MAPS_LIBRARIES: ("places" | "geometry")[] = ["places", "geometry"];

interface GoogleMapsViewProps {
  sx?: SxProps<Theme>;
  height?: string;
  width?: string;
  routes: CircuitMap[];
  Submodule: MapType;
  onMapClick?: (event: google.maps.MapMouseEvent) => void;
  markers?: RouteMarker[];
  defaultCenter?: google.maps.LatLngLiteral;
  defaultZoom?: number;
  options?: google.maps.MapOptions;
  activeDepartement?: string;
  onDepartementChange?: (departement: string) => void;
  isGeoloc?: boolean;
  vehiclePositions?: any;
  selectedVehicule?: string;
  selectedChauffeur?: string;
  onVehiclePositionsUpdate?: (positions: any) => void;
  onMapLoaded?: () => void;
  children?: React.ReactNode;
}

export default function GoogleMapsView({
  sx,
  height = 'calc(100vh - 240px)',
  width = '100%',
  routes = [],
  Submodule,
  onMapClick,
  markers = [],
  defaultCenter = DEFAULT_CENTER,
  defaultZoom = DEFAULT_ZOOM,
  onMapLoaded,
  children,
}: GoogleMapsViewProps) {
  const { isLoaded, loadError } = useJsApiLoader({
    googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY || '',
    libraries: GOOGLE_MAPS_LIBRARIES,
  });

  const [map, setMap] = useState<google.maps.Map | null>(null);
  const [selectedMarker, setSelectedMarker] = useState<string | null>(null);
  const mapCenterRef = useRef(defaultCenter);
  const [mapZoom, setMapZoom] = useState(defaultZoom);

  // Enhanced map load handler
  const handleMapLoad = useCallback((mapInstance: google.maps.Map) => {
    setMap(mapInstance);
    
    // Add map event listeners
    mapInstance.addListener('center_changed', () => {
      const center = mapInstance.getCenter();
      if (center) {
        const newCenter = { lat: center.lat(), lng: center.lng() };
        if (newCenter.lat !== mapCenterRef.current.lat || newCenter.lng !== mapCenterRef.current.lng) {
          mapCenterRef.current = newCenter;
        }
      }
    });

    mapInstance.addListener('zoom_changed', () => {
      const newZoom = mapInstance.getZoom() || defaultZoom;
      setMapZoom(newZoom);
    });

    onMapLoaded?.();
  }, [onMapLoaded, defaultZoom]);

  // Fit bounds when markers change
  useEffect(() => {
    if (map && markers.length > 0) {
      const bounds = new google.maps.LatLngBounds();
      markers.forEach((marker) => {
        if (marker.position && !isNaN(marker.position.lat) && !isNaN(marker.position.lng)) {
          bounds.extend(marker.position);
        }
      });
      map.fitBounds(bounds);
    }
  }, [map, markers]);

  const handleMapClick = useCallback((event: google.maps.MapMouseEvent) => {
    if (onMapClick) {
      onMapClick(event);
    }
  }, [onMapClick]);

  if (!isLoaded) return <Box>Loading...</Box>;

  return (
    <Box sx={{ position: 'relative', width, height, ...sx }}>
      <GoogleMap
        mapContainerStyle={{ width, height }}
        center={mapCenterRef.current}
        zoom={mapZoom}
        onLoad={handleMapLoad}
        onClick={handleMapClick}
        options={{
          zoomControl: true,
          streetViewControl: false,
          mapTypeControl: false,
          fullscreenControl: true,
          gestureHandling: 'cooperative',
          styles: [
            {
              featureType: 'poi',
              elementType: 'labels',
              stylers: [{ visibility: 'off' }]
            }
          ]
        }}
      >{children}
        {/* Render polylines for routes */}
        {routes.map((route) => (
  <ConditionalComponent key={route.id} isValid={!!route.path}>
    <MapPolyline
      path={route.path!} // <--- Assert that path is defined
      color={route.color || '#000000'}
      index={0}
      onPolylineClick={() => {}}
    />
  </ConditionalComponent>
))}


        

        {/* Render markers */}
        {markers.map((marker, index) => {
          if (!marker.position || 
              typeof marker.position.lat !== 'number' || 
              typeof marker.position.lng !== 'number' ||
              isNaN(marker.position.lat) || 
              isNaN(marker.position.lng)) {
            return null;
          }

          return (
            <Marker
              key={marker.id}
              position={marker.position}
              icon={typeof marker.icon === 'string' ? marker.icon : marker.icon}
              title={marker.title}
              label={{
                text: (index + 1).toString(),
                color: '#FFFFFF',
                fontWeight: 'bold'
              }}
              onClick={() => setSelectedMarker(marker.id)}
            >
              {selectedMarker === marker.id && (
                <InfoWindow
                  position={marker.position}
                  onCloseClick={() => setSelectedMarker(null)}
                >
                  <div>
                    <h3 style={{ margin: '0 0 8px 0', color: '#6E37F0' }}>{marker.title}</h3>
                    <p style={{ margin: 0 }}>Point {index + 1}</p>
                  </div>
                </InfoWindow>
              )}
            </Marker>
          );
        })}
      </GoogleMap>
    </Box>
  );
}