import { FC, useEffect, useRef } from 'react';

import { useMap } from '@vis.gl/react-google-maps';

type ConnectionLineProps = {
  path: google.maps.LatLngLiteral[];
  strokeColor: string;
  strokeOpacity: number;
  strokeWeight: number;
  onMouseOver?: () => void;
  onMouseOut?: () => void;
};

// Polyline component for connecting marking location to site
const ConnectionLine: FC<ConnectionLineProps> = ({
  path,
  strokeColor,
  strokeOpacity,
  strokeWeight,
  onMouseOver,
  onMouseOut,
}) => {
  const map = useMap();
  const polylineRef = useRef<google.maps.Polyline | null>(null);
  const listenersRef = useRef<google.maps.MapsEventListener[]>([]);

  useEffect(() => {
    if (!map) return;

    if (!polylineRef.current) {
      polylineRef.current = new google.maps.Polyline({
        map,
        path,
        strokeColor,
        strokeOpacity,
        strokeWeight,
        geodesic: true,
      });

      // Add event listeners
      if (onMouseOver) {
        listenersRef.current.push(
          polylineRef.current.addListener('mouseover', onMouseOver),
        );
      }
      if (onMouseOut) {
        listenersRef.current.push(
          polylineRef.current.addListener('mouseout', onMouseOut),
        );
      }
    } else {
      polylineRef.current.setPath(path);
      polylineRef.current.setOptions({
        strokeColor,
        strokeOpacity,
        strokeWeight,
      });
    }

    return () => {
      // Remove listeners
      listenersRef.current.forEach(listener => listener.remove());
      listenersRef.current = [];

      if (polylineRef.current) {
        polylineRef.current.setMap(null);
        polylineRef.current = null;
      }
    };
  }, [map, path, onMouseOver, onMouseOut]);

  return null;
};

export default ConnectionLine;
