import { useAmap, usePlugins } from '@amap/amap-react';
import { FC, memo, useEffect, useRef } from 'react';
import { AMapGeocoderGetAddressResult } from '../../types';

export interface DageMapGeocoderProps {
  position: number[];
  city?: number | string;
  onChange?: (res: AMapGeocoderGetAddressResult) => void;
}

export const DageMapGeocoder: FC<DageMapGeocoderProps> = memo(({ city, position, onChange }) => {
  const map = useAmap();
  const AMap = usePlugins(['AMap.Geocoder']);
  const geocoder = useRef<any>();

  useEffect(() => {
    if (!map || !AMap) return;
    // @ts-ignore
    geocoder.current = new AMap.Geocoder({
      city,
    });
    map.add(geocoder.current);

    return () => {
      map.remove(geocoder.current);
    };
  }, [map, AMap, city]);

  useEffect(() => {
    geocoder.current &&
      geocoder.current.getAddress(
        position,
        (status: string, result: AMapGeocoderGetAddressResult) => {
          if (status === 'complete' && result.info === 'OK') {
            onChange?.(result);
          }
        },
      );
  }, [position, onChange]);

  return null;
});
