import React, { FC, useEffect, useState } from 'react';
import GoogleMapReact from 'google-map-react';
import MarkerSVG from '../../assets/icons/marker.svg';
import css from './index.module.css';

export interface AddressMapProps {
  googleApiKey?: string;
  markerName?: string;
  position: CoordsProps;
}
export interface CoordsProps {
  latitude: number;
  longitude: number;
}
export interface GeoPositionProps {
  center: CoordsProps;
  zoom: number;
}
export const Marker = (props): JSX.Element => {
  const { name } = props;
  return (
    <div className={css.booking__marker} title={name}>
      <MarkerSVG className={css.booking__markerIcon} />
    </div>
  );
};

const AddressMap: FC<AddressMapProps> = ({
  googleApiKey,
  markerName,
  position,
}) => {
  const [geoPosition, setGeoPosition] = useState<GeoPositionProps>(null);
  useEffect(() => {
    setGeoPosition({
      center: position,
      zoom: 16,
    });
  }, [position]);

  return (
    <>
      {geoPosition && geoPosition.center && (
        <div className={css.booking__map}>
          {geoPosition.center.latitude && geoPosition.center.longitude && (
            <GoogleMapReact
              bootstrapURLKeys={{ key: googleApiKey }}
              defaultCenter={{
                lat: geoPosition.center.latitude,
                lng: geoPosition.center.longitude,
              }}
              defaultZoom={geoPosition.zoom}
            >
              <Marker
                lat={geoPosition.center.latitude}
                lng={geoPosition.center.longitude}
                name={markerName}
              />
            </GoogleMapReact>
          )}
        </div>
      )}
    </>
  );
};

export default AddressMap;
