import React, { useState, useRef, useEffect, useLayoutEffect } from 'react';
import { render } from 'react-dom';
import useUpdateEffect from '@umijs/hooks/es/useUpdateEffect';
import { useEvents, useMap } from '@/hooks';

export interface InfoWindowProps
  extends Omit<AMap.InfoOptions, 'content' | 'anchor' | 'size'> {
  anchor?: AMap.Anchor;
  height?: number;
  size?: AMap.Vector2;
  visible?: boolean;
  events?: any;
}

export const InfoWindow: React.FC<InfoWindowProps> = ({
  visible,
  events,
  height,
  children,
  ...options
}) => {
  const { map } = useMap();
  const el = useRef<HTMLDivElement>(document.createElement('div'));
  const [infoWindow] = useState(() => new AMap.InfoWindow(options));

  useEvents(events, infoWindow);

  useLayoutEffect(() => {
    render(<>{children}</>, el.current, () => {
      infoWindow.setContent(el.current);
    });
  });

  useEffect(() => {
    if (map && visible && options.position) {
      infoWindow.open(map, options.position, height || 0);
    } else {
      infoWindow.close();
    }
  }, [map, visible, infoWindow, JSON.stringify(options.position), height]);

  useUpdateEffect(() => {
    if (infoWindow && options?.anchor) {
      infoWindow.setAnchor(options?.anchor);
    }
  }, [infoWindow, options.anchor]);

  useUpdateEffect(() => {
    if (infoWindow && options?.size) {
      infoWindow.setSize(options?.size);
    }
  }, [infoWindow, JSON.stringify(options.size)]);

  return null;
};
