/* eslint-disable no-unused-expressions */
import React from 'react';
import ReactDOM from 'react-dom';

export interface ModalInterface {
  onCloseCallback?: () => unknown;
}
export default function Modal({ onCloseCallback, children }: ModalInterface & React.PropsWithChildren) {
  const modalRef = React.useRef<HTMLDivElement>(null);
  const el = React.useRef(document.createElement('div'));

  const closeModal = () => {
    el.current.remove();
    if (typeof onCloseCallback !== 'undefined') onCloseCallback();
  };
  React.useEffect(() => {
    const portal = document.getElementById('root');
    portal?.appendChild(el.current);

    return () => {
      if (typeof onCloseCallback !== 'undefined') onCloseCallback();
      return el.current?.remove();
    };
  }, []);
  return ReactDOM.createPortal(
    <div
      onClick={closeModal}
      ref={modalRef}
      className='fixed top-0 left-0 z-20 w-screen h-screen p-2 rounded-md text-black flex justify-center items-center'
    >
      <div
        className='max-w-[60%] max-h-[90%] p-4 rounded-sm shadow-lg bg-white overflow-auto'
        onClick={(e) => {
          e.stopPropagation();
        }}
      >
        {children}
      </div>
    </div>,
    el.current,
  );
}
