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;
  onError?: () => void;
}

export const DageMapGeocoder: FC<DageMapGeocoderProps> = memo(
  ({ city, position, onError, 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);
            } else {
              onError?.();
            }
          }
        );
    }, [position, onChange]);

    return null;
  },
  (prevProps, nextProps) =>
    prevProps.position[0] === nextProps.position[0] &&
    prevProps.position[1] === nextProps.position[1]
);
