import { useEffect, useRef, useState } from "react";
import styles from "./styles.module.scss";

interface IVideoOverlayProps {
  isShow: boolean;
  setIsShow: React.Dispatch<React.SetStateAction<boolean>>;
  animationDuration?: number;
  children?: React.ReactNode;
}

function VideoOverlay({
  isShow,
  setIsShow,
  animationDuration = 5000,
  children,
}: IVideoOverlayProps) {
  const timeoutRef = useRef<NodeJS.Timeout>();
  const [animationDurationLocal, setAnimationDurationLocal] =
    useState(animationDuration);

  const click = () => {
    if (timeoutRef.current) clearTimeout(timeoutRef.current);
    setAnimationDurationLocal((prev) => prev + animationDuration);
    timeoutRef.current = setTimeout(() => {
      setIsShow(false);
    }, animationDuration);
  };

  useEffect(() => {
    if (!isShow) return;
    console.log("start ");

    timeoutRef.current = setTimeout(() => {
      setIsShow(false);
    }, animationDuration);
    return () => {
      if (timeoutRef.current) clearTimeout(timeoutRef.current);
    };
  }, [animationDuration, isShow, setIsShow]);

  return (
    <>
      {isShow && (
        <div
          className={styles.overlay}
          style={{
            animationDelay: `0s, ${animationDurationLocal - 500}ms`,
          }}
          onClick={click}
        >
          <div
            className={styles.content}
            style={{
              animationDelay: `0s, ${animationDurationLocal - 500}ms`,
            }}
          >
            {children}
          </div>
        </div>
      )}
    </>
  );
}

export default VideoOverlay;
