'use client';

import { useEffect, useState, useRef } from 'react';
import { Marker } from '@react-google-maps/api';
import { VehiclePosition } from '@/shared/types/Maps';
import { DetailsPopover } from '@/shared/components/custom-popover/DetailsPopover';
import { StatusColor } from '@/shared/sections/chauffeur/planingChauffeur/utils/schedule-utils';
import { usePopover } from '@/shared/components/custom-popover';
import { faClock, faUser, faCar } from '@fortawesome/free-solid-svg-icons';

interface VehicleMarkerProps {
  position: VehiclePosition;
  selected: boolean;
  onClick: () => void;
  departureDate?: string;
  chauffeurNom?: string;
  chauffeurPrenom?: string;
}

const VehicleMarker = ({
  position,
  selected,
  onClick,
  departureDate,
  chauffeurNom,
  chauffeurPrenom
}: VehicleMarkerProps) => {
  const [icon, setIcon] = useState<google.maps.Icon>({
    url: '/assets/icons/maps/dynamic/vehicule.svg',
    scaledSize: new window.google.maps.Size(40, 40),
    anchor: new window.google.maps.Point(20, 20),
  });

  const popover = usePopover();
  const markerRef = useRef<google.maps.Marker | null>(null);

  useEffect(() => {
    if (markerRef.current) {
      setTimeout(() => {
        const markers = document.querySelectorAll(`[src="${icon.url}"]`);
        markers.forEach(marker => {
          (marker as HTMLElement).style.transform = `rotate(${position.rotation}deg)`;
          (marker as HTMLElement).style.transition = 'transform 0.5s ease-in-out';
        });
      }, 100); 
    }
  }, [position.rotation, icon.url]);

  const handleMarkerMouseOver = (event: google.maps.MapMouseEvent) => {
    const markerElement = event.domEvent.target as HTMLElement;
    popover.setOpen(markerElement);
  };

  const handleMarkerMouseOut = () => {
    popover.onClose();
  };

  const handleMarkerClick = () => {
    onClick();
  };

  const popoverData = [
    {
      icon: faUser,
      value: `${chauffeurPrenom || ''} ${chauffeurNom || ''}`.trim() || 'Non spécifié'
    },
    {
      icon: faClock,
      value: departureDate
        ? new Date(departureDate).toLocaleTimeString('fr-FR', {
            hour: '2-digit',
            minute: '2-digit'
          })
        : '-'
    },
    {
      icon: faCar,
      value: position.vehicleType || 'Non spécifié'
    }
  ];

  return (
    <>
      <Marker
        position={{ lat: position.lat, lng: position.lng }}
        icon={icon}
        onClick={handleMarkerClick}
        onMouseOver={handleMarkerMouseOver}
        onMouseOut={handleMarkerMouseOut}
        onLoad={(marker) => (markerRef.current = marker)}
        zIndex={selected ? 1000 : 1}
      />
      <DetailsPopover
        anchorEl={popover.open}
        onClose={popover.onClose}
        color={StatusColor.PRIMARY}
        data={popoverData}
        arrow={false}
      />
    </>
  );
};

export default VehicleMarker;