import { useEffect, useRef, useState } from "react";
import { m, useAnimate } from "framer-motion";

import { useWindowSize } from "@/hooks";
import { useStore } from "@/store";

import styles from "./styles.module.scss";

interface KeyholeAnimationProps {
  startAnimation?: boolean;
}

interface SVGsizeInterface {
  w: number | string;
  h: number | string;
}

export const KeyholeAnimation = ({
  startAnimation = false,
}: KeyholeAnimationProps) => {
  const [scope, animate] = useAnimate();
  const maskRef = useRef(null);

  const isRestarting = useStore.use.isRestarting();
  const setStep = useStore.use.setStep();
  const setRestarting = useStore.use.setIsRestarting();
  const [scopeOverlay, animateOverlay] = useAnimate();

  const progress = useStore.use.progress();

  const windowSize = useWindowSize();

  const [isActive, setIsActive] = useState<boolean>(true);
  const [animationCompleted, setAnimationCompleted] = useState<boolean>(false);

  const resetQuiz = useStore.use.resetQuiz();

  const [svgSize, setSvgSize] = useState<SVGsizeInterface>({
    w: "100%",
    h: "100%",
  });

  useEffect(() => {
    setIsActive(progress < 1 || !animationCompleted);
  }, [progress, animationCompleted, setIsActive]);

  useEffect(() => {
    if (isActive) {
      //console.log("Loading…", progress);
      setSvgSize({ w: windowSize.width, h: windowSize.height });

      //TODO: Replace animation by a CSS property
      const animationSequence = async () => {
        await Promise.all([
          animate(
            "#heart",
            {
              x: windowSize.width / 2 - 50,
              y: windowSize.height / 2 - 50,
              scale: 1,
            },
            { duration: 0 },
          ),

          animate(
            "#progress",
            { height: 100 - progress * 100 },
            { duration: 0.3 },
          ),
        ]);

        if (startAnimation) {
          await Promise.all([
            // Scale up
            animate(
              maskRef.current,
              { scale: [1, 150] },
              {
                duration: 2.5,
                ease: "easeInOut",
                onComplete: () => {
                  setAnimationCompleted(true);
                },
              },
            ),
          ]);

          // Hide mask after intro animation
          if (!scope.current) return;
          await animate(
            "#mask-container",
            { opacity: 0 },
            {
              duration: 0,
            },
          );
        }
      };
      animationSequence();
    }
  }, [
    scope,
    animate,
    startAnimation,
    isActive,
    windowSize,
    progress,
    setAnimationCompleted,
  ]);

  useEffect(() => {
    if (isRestarting) {
      setSvgSize({ w: windowSize.width, h: windowSize.height });

      const animationSequence = async () => {
        const scale = Math.max(windowSize.width, windowSize.height);
        const initSize = 60;
        const startScale = 0.01;
        const endScale = scale / initSize;
        const duration = 0.5;
        await Promise.all([
          animateOverlay(
            "#heartOverlay",
            {
              x: windowSize.width / 2 - 50,
              y: windowSize.height / 2 - 50,
              scale: endScale,
            },
            { duration: 0 },
          ),
        ]);

        await Promise.all([
          // Scale down
          animateOverlay(
            "#heartOverlay",
            {
              scale: [endScale, startScale],
            },
            {
              duration,
              ease: "easeOut",
              onComplete: () => {
                console.log("CAMBIO STEP");
                resetQuiz(0);
              },
            },
          ),
        ]);

        await Promise.all([
          // Scale up
          animateOverlay(
            "#heartOverlay",
            { scale: [startScale, endScale] },
            {
              duration,
              delay: 0.7,
              ease: "easeIn",
              onComplete: () => {
                console.log("CAMBIO STEP");
                setRestarting(false);
              },
            },
          ),
        ]);

        // Hide mask after intro animation
        if (!scope.current) return;
        await animateOverlay(
          "#mask-containerOverlay",
          { opacity: 0 },
          {
            duration: 0,
          },
        );
      };

      animationSequence();
    }
  }, [
    isRestarting,
    scope,
    animateOverlay,
    startAnimation,
    windowSize,
    setRestarting,
    setStep,
    resetQuiz,
  ]);

  return (
    <>
      {isActive && (
        <div ref={scope} className={styles.keyholeAnimation}>
          <m.div
            ref={maskRef}
            className={styles.logoAnimationWrapper}
            id="mask-container"
            role="progressbar"
            aria-labelledby="Loading page"
            tabIndex={isActive ? 0 : -1}
          >
            <svg
              className={styles.logoAnimation}
              width={svgSize.w}
              height={svgSize.h}
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              preserveAspectRatio="xMidYMid slice"
            >
              <defs>
                <mask id="mask" className={styles.mask}>
                  <rect width="100%" height="100%" fill="white" />
                  <m.path
                    className={styles.heart}
                    id="heart"
                    d="M50 31.161C50 13.9513 38.8071 0 25 0C11.1929 0 0 13.9513 0 31.161C-6.87345e-06 60.4626 31.7319 82.6305 44.6378 90.4347C47.9967 92.4659 52.0325 92.5275 55.4357 90.5774C68.3881 83.1556 100 61.8938 100 31.161C100 13.9513 88.8071 0 75 0C61.1929 0 50 13.9513 50 31.161Z"
                    fill="black"
                  />
                </mask>
              </defs>

              <rect
                id="progress"
                width="100"
                height="100"
                x="50%"
                y="50%"
                transform="translate(-50 -50)"
                fill="#3F4D8F"
              />
              <rect
                className={styles.background}
                width="100%"
                height="100%"
                mask="url(#mask)"
              />
            </svg>
          </m.div>
        </div>
      )}
      {isRestarting && (
        <div ref={scopeOverlay} className={styles.overlayTransition}>
          <m.div
            className={styles.logoAnimationWrapperOverlay}
            id="mask-containerOverlay"
            role="progressbar"
            aria-labelledby="Loading page"
            tabIndex={isActive ? 0 : -1}
          >
            <svg
              className={styles.logoAnimationOverlay}
              width={svgSize.w}
              height={svgSize.h}
              viewBox={`0 0 ${svgSize.w} ${svgSize.h}`}
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
              preserveAspectRatio="xMidYMid slice"
            >
              <defs>
                <mask id="maskOverlay" className={styles.maskOverlay}>
                  <rect width="100%" height="100%" fill="white" />
                  <m.path
                    style={{ originX: "50px", originY: "46px" }}
                    className={styles.heart}
                    id="heartOverlay"
                    d="M50 31.161C50 13.9513 38.8071 0 25 0C11.1929 0 0 13.9513 0 31.161C-6.87345e-06 60.4626 31.7319 82.6305 44.6378 90.4347C47.9967 92.4659 52.0325 92.5275 55.4357 90.5774C68.3881 83.1556 100 61.8938 100 31.161C100 13.9513 88.8071 0 75 0C61.1929 0 50 13.9513 50 31.161Z"
                    fill="black"
                  />
                </mask>
              </defs>

              <rect
                className={styles.background}
                width="100%"
                height="100%"
                mask="url(#maskOverlay)"
              />
            </svg>
          </m.div>
        </div>
      )}
    </>
  );
};

export default KeyholeAnimation;
