import { useMemoizedFn, useMount, useUnmount } from 'ahooks';
import { useRef, forwardRef, useImperativeHandle, Ref } from 'react';

function ResourceDialog(
  {
    src,
    open = false,
    componentDid,
    loading = true,
    storeUrl = '',
    onClose = () => {},
    onComplete = () => {},
    onLoad = () => {},
  }: {
    src: string;
    componentDid: string;
    open?: boolean;
    loading?: boolean;
    storeUrl?: string;
    onLoad?: () => void;
    onClose?: () => void;
    onComplete?: () => void;
  },
  ref: Ref<{
    selectBlocklet: (blockletMeta: any) => void;
  }>
) {
  const iframeRef = useRef<HTMLIFrameElement>(null);

  const listener = useMemoizedFn((event: MessageEvent) => {
    if (open) {
      if (event?.data?.event === 'resourceDialog.close') {
        onClose();
      }
      if (event?.data?.event === 'resourceDialog.complete') {
        onComplete();
      }
      if (event?.data?.event === 'resourceDialog.loaded') {
        onLoad();
      }
    }
  });

  useMount(() => {
    window.addEventListener('message', listener);
  });

  useUnmount(() => {
    window.removeEventListener('message', listener);
  });

  useImperativeHandle(ref, () => ({
    selectBlocklet: (blockletMeta: any) => {
      if (iframeRef.current?.contentWindow) {
        iframeRef.current.contentWindow.postMessage(
          {
            event: 'resourceDialog.select',
            data: blockletMeta,
            componentDid,
            storeUrl,
          },
          '*'
        );
      }
    },
  }));

  if (!open) {
    return null;
  }

  return (
    <iframe
      ref={iframeRef}
      src={src}
      title="Resource Dialog"
      style={{
        position: 'fixed',
        top: 0,
        left: loading ? '-100vw' : 0,
        width: '100vw',
        height: '100vh',
        zIndex: 9999,
        backgroundColor: 'transparent',
        border: 'none',
      }}
    />
  );
}

export default forwardRef(ResourceDialog);
