import { ReactElement, useEffect, useState } from "react";

interface TimedRenderProps {
  /**
   * A React element to conditionally render.
   */
  children: ReactElement;
  /**
   * Trigger to start rendering the child.
   */
  startRender: boolean;
  /**
   * Trigger for starting the timeout to unmount the child.
   */
  stopRender: boolean;
  /**
   * How long the timeout should last before the child unmounts.
   */
  delay: number;
}

export const TimedRender = ({
  children,
  startRender,
  stopRender,
  delay
}: TimedRenderProps) => {
  const [shouldRender, setShouldRender] = useState<boolean>(false);

  useEffect(() => {
    startRender && setShouldRender(true);

    if (stopRender) {
      const timer = setTimeout(() => {
        setShouldRender(false);
      }, delay);

      return () => clearTimeout(timer);
    }
  }, [startRender, stopRender, delay]);

  if (shouldRender) return children;

  return <></>;
};
