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

// avoid re-rendering with memo(..., () => true)
// this reduces reusability of this component, but that's fine for this
export default React.memo(({
  onMarkerMoved
}) => {
  const mapDivRef = useRef(null);
  useEffect(() => {
    const googleMap = new google.maps.Map(mapDivRef.current, {
      center: { lat: 25, lng: -25 },
      zoom: 0,
      disableDefaultUI: true,
      fullscreenControl: true,
    });

    if (onMarkerMoved) {
      googleMap.addListener("click", ({ latLng }) => {
        if (mapDivRef.current.mapMarker) {
          mapDivRef.current.mapMarker.setMap(null);
        }
        mapDivRef.current.mapMarker = new google.maps.Marker({ map: googleMap, position: latLng });
        if (onMarkerMoved) {
          onMarkerMoved({ lat: latLng.lat(), lng: latLng.lng() });
        }
      });
    }
  });

  return <div className="map-div" ref={mapDivRef} />
}, () => true);
