import React, { useMemo, useState } from 'react';
import ReactDOM from 'react-dom';
import { useDidUpdateEffect, useEventListener } from '@devesharp/react-hooks';
import { IModalProps } from './Modal.interface';
import { ModalContainerStyle, ModalStyle } from './Modal.style';

/**
 * Todo: verifcar se modal continua funcionando no stories
 * @param props
 * @constructor
 */
export const Modal: React.FunctionComponent<IModalProps> & { Body: React.FunctionComponent<any> } = function Modal(
   props,
) {
   const { children, show, onRequestClose, animation = 'fade', transparent = false, ...rest } = props;

   const [internalShow, setInternalShow] = useState(show);
   const [closing, setClosing] = useState(false);

   useDidUpdateEffect(() => {
      if (!show) {
         setClosing(true);

         setTimeout(() => {
            setInternalShow(false);
            if (onRequestClose) onRequestClose();
         }, 300);
      } else {
         setClosing(false);
         setInternalShow(true);
      }
   }, [show]);

   useEventListener('keydown.esc', () => {
      if (onRequestClose) onRequestClose();
   });

   return ReactDOM.createPortal(
      <>
         {internalShow && (
            <ModalContainerStyle animation={animation} {...rest}>
               <div className={`ds-modal-container ${closing && ' closing'}`}>
                  {!transparent && <div className="bg-background" onClick={() => onRequestClose && onRequestClose()} />}
                  <>{children}</>
               </div>
            </ModalContainerStyle>
         )}
      </>,
      document.querySelector('body'),
   );
} as any;

Modal.Body = function ModalBody(props): any {
   const { children, show, name, onRequestClose, ...rest } = props;

   return (
      <>
         <ModalStyle {...rest}>{children}</ModalStyle>
      </>
   );
};
