import React, { useEffect, useLayoutEffect, useRef, useState } from 'react';
import useResizeObserver from '@react-hook/resize-observer';
import { IAnimationInOutProps } from './AnimationInOut.interface';
import AnimationInOutStyle from './AnimationInOut.style';

export function AnimationInOut({
   visible = true,
   children,
   keepFirstAnimation = false,
   durationIn = 300,
   durationOut = 300,
   animationOut = 'fade',
   animationIn = 'fade',
}: IAnimationInOutProps): JSX.Element {
   const ref = useRef<HTMLDivElement>();

   const [height, setHeight] = useState(0);
   const [enableFirstAnimation, setEnableFirstAnimation] = useState(!keepFirstAnimation);

   useResizeObserver(ref, (entry) => setHeight(entry.contentRect.height));

   // if (animationOut === 'height' && !ref.current?.clientHeight) visible = false;

   useLayoutEffect(() => {
      setHeight(ref.current?.clientHeight);
   }, []);

   // Para não h
   useLayoutEffect(() => {
      if (!visible) {
         setEnableFirstAnimation(true);
      }
   }, [visible]);

   return (
      <AnimationInOutStyle
         visible={visible}
         durationIn={enableFirstAnimation ? (Array.isArray(durationIn) ? durationIn : [durationIn]) : [0]}
         durationOut={enableFirstAnimation ? (Array.isArray(durationOut) ? durationOut : [durationOut]) : [0]}
         animationOut={Array.isArray(animationOut) ? animationOut : [animationOut]}
         animationIn={Array.isArray(animationIn) ? animationIn : [animationIn]}
         style={{ height }}
      >
         <div ref={ref}>{children}</div>
      </AnimationInOutStyle>
   );
}
