/// <reference types="google.maps" />
import { FC, useEffect, useRef } from 'react';

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

type ToleranceCircleProps = {
  center: google.maps.LatLngLiteral;
  radius: number;
  strokeColor: string;
  strokeOpacity: number;
  strokeWeight: number;
  fillColor: string;
  fillOpacity: number;
  onMouseOver?: () => void;
  onMouseOut?: () => void;
};

// Circle component for tolerance radius
const ToleranceCircle: FC<ToleranceCircleProps> = ({
  center,
  radius,
  strokeColor,
  strokeOpacity,
  strokeWeight,
  fillColor,
  fillOpacity,
  onMouseOver,
  onMouseOut,
}) => {
  const map = useMap();
  const circleRef = useRef<google.maps.Circle | null>(null);
  const listenersRef = useRef<google.maps.MapsEventListener[]>([]);

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

    // Create circle if it doesn't exist
    if (!circleRef.current) {
      circleRef.current = new google.maps.Circle({
        map,
        center,
        radius,
        strokeColor,
        strokeOpacity,
        strokeWeight,
        fillColor,
        fillOpacity,
      });

      // Add event listeners
      if (onMouseOver) {
        listenersRef.current.push(
          circleRef.current.addListener('mouseover', onMouseOver),
        );
      }
      if (onMouseOut) {
        listenersRef.current.push(
          circleRef.current.addListener('mouseout', onMouseOut),
        );
      }
    } else {
      // Update existing circle
      circleRef.current.setCenter(center);
      circleRef.current.setRadius(radius);
      circleRef.current.setOptions({
        strokeColor,
        strokeOpacity,
        strokeWeight,
        fillColor,
        fillOpacity,
      });
    }

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

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

  return null;
};

export default ToleranceCircle;
