import React, { useEffect, useMemo, useRef, 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,
      disableAnimation = false,
      ...rest
   } = props;

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

   const timeoutRef = useRef<any>();

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

         if (disableAnimation) {
            setInternalShow(false);
            if (onRequestClose) onRequestClose();
         } else {
            if (timeoutRef.current) clearTimeout(timeoutRef.current);

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

   // Limpar timeout
   useEffect(() => () => timeoutRef.current && clearTimeout(timeoutRef.current), []);

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

   return ReactDOM.createPortal(
      <>
         {internalShow && (
            <ModalContainerStyle animation={animation} disableAnimation={disableAnimation} {...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>
      </>
   );
};
