import React, { useMemo, useState } from 'react';
import ReactDOM from 'react-dom';
import { useDidUpdateEffect } 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> } = (props) => {
   const { children, show, onRequestClose = () => {}, onHide, animation = 'fade', ...rest } = props;

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

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

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

   return ReactDOM.createPortal(
      <>
         {internalShow && (
            <ModalContainerStyle animation={animation} {...rest}>
               <div className={`ds-modal-container ${closing && ' closing'}`}>
                  <>{children}</>
               </div>
            </ModalContainerStyle>
         )}
      </>,
      document.querySelector('body'),
   );
};

Modal.Body = function ModalBody(props): JSX.Element {
   const { children, show, name, onHide, ...rest } = props;

   return (
      <>
         <ModalStyle {...rest}>{children}</ModalStyle>
         {/*<div*/}
         {/*   className="bg-background"*/}
         {/*   data-testid="bg-modal"*/}
         {/*   onClick={() => {*/}
         {/*      if (onRequestClose) onRequestClose();*/}
         {/*   }}*/}
         {/*/>*/}
         {/*<div className="modal-content">*/}
         {/*   <>{children}</>*/}
         {/*</div>*/}
      </>
   );
};
