import { useRef, useEffect } from "react";
/* global google */

const useClickMarker = (map, onMove) => {
  const marker = useRef(null);
  useEffect(() => {
    const listener = map.current.addListener("click", ({ latLng }) => {
      if (marker.current) {
        marker.current.setMap(null);
      }
      marker.current = new google.maps.Marker({
        map: map.current,
        position: latLng,
      });
      onMove({ lat: latLng.lat(), lng: latLng.lng() }, marker.current);
    });

    return () => {
      google.maps.event.removeListener(listener);
    };
  }, [map, onMove]);
};

export default useClickMarker;
