'use client';

import { useState, useCallback, useRef, useEffect, useMemo } from 'react';
import { Box, type SxProps, type Theme } from '@mui/material';
import { GoogleMap, Marker, InfoWindow } from '@react-google-maps/api';
import { CircuitMap, RouteMarker, MapType } from '@/shared/types/Maps';

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

const DEFAULT_ZOOM = 18;

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

  const handleMapLoad = useCallback((mapInstance: google.maps.Map) => {
    setMap(mapInstance);
    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]);

  useEffect(() => {
    if (map) {
      const bounds = new google.maps.LatLngBounds();
      let hasBoundsContent = false

      markers.forEach((marker) => {
        if (marker.position && !isNaN(marker.position.lat) && !isNaN(marker.position.lng)) {
          bounds.extend(marker.position);
          hasBoundsContent = true
        }
      })

      routes.forEach((route) => {
        if (route.path && route.path.length > 0) {
          route.path.forEach((point) => {
            if (!isNaN(point.lat) && !isNaN(point.lng)) {
              bounds.extend(point)
              hasBoundsContent = true
            }
          })
        }
      })

      if (hasBoundsContent) {
        map.fitBounds(bounds)
      }
    }
  }, [map, markers, routes])

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

  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}
      
        {routes.map((route) => (
          <ConditionalComponent key={route.id} isValid={!!route.path && route.path.length > 0}>
            <MapPolyline
              path={route.path!}
              color={route.color || '#000000'}
              index={0}
              onPolylineClick={() => {}}
            />
          </ConditionalComponent>
        ))}

        {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>
  );
}