import { useEffect, useMemo, useRef, useState } from "react";

import { Step } from "@/hooks/palmistry/use-steps";
import useSteps from "@/hooks/palmistry/use-steps";
import ScannedPhoto from "@/components/palmistry/scanned-photo/scanned-photo";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import { IPalmistryLine } from "@/api/resources/Palmistry";
import { IPalmistryFingerLocal } from "@/store/palmistry";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";

const drawElementChangeDelay = 1500;
const startDelay = 500;
// const goNextDelay = 12000;

export default function StepScanPhoto() {
  const { translate } = useTranslations(ELocalesPlacement.PalmistryV0);
  const steps = useSteps();
  const navigate = useNavigate();

  const storedPhoto = steps.getStoredValue(Step.Upload);

  const lines = useSelector(selectors.selectPalmistryLines);
  const fingers = useSelector(selectors.selectPalmistryFingers);
  const drawElements = useMemo(() => [...fingers, ...lines], [fingers, lines]);

  const [currentElementIndex, setCurrentElementIndex] = useState(0);
  const [smallPhotoState, setSmallPhotoState] = useState(false);
  const [title, setTitle] = useState("");
  const [shouldDisplayPalmLines, setShouldDisplayPalmLines] = useState(false);
  const changeTitleTimeOut = useRef<NodeJS.Timeout>();

  const prevElementIndex = useRef<number | null>(null);

  const goNextElement = (delay: number) => {
    changeTitleTimeOut.current = setTimeout(() => {
      const title =
        (drawElements[currentElementIndex] as IPalmistryFingerLocal).name ||
        drawElements[currentElementIndex].name;
      setTitle(translate(title));
      setCurrentElementIndex((prevState) => prevState + 1);
    }, delay);
  };

  useEffect(() => {
    if (!drawElements.length) {
      return navigate(routes.client.palmistryUpload());
    }
  }, [drawElements, navigate]);

  useEffect(() => {
    // if (currentElementIndex === 0) {
    //   new Promise((resolve) => setTimeout(resolve, startDelay));
    // }
    if (
      currentElementIndex < drawElements?.length &&
      currentElementIndex !== prevElementIndex.current
    ) {
      prevElementIndex.current = currentElementIndex;
      goNextElement(drawElementChangeDelay);
      setShouldDisplayPalmLines(
        lines?.includes(drawElements[currentElementIndex] as IPalmistryLine)
      );
    }

    if (currentElementIndex >= drawElements?.length) {
      const toSmallTimeOut = setTimeout(() => {
        setSmallPhotoState(true);
      }, drawElementChangeDelay);
      const goNextTimeOut = setTimeout(
        steps.goNext,
        drawElementChangeDelay * drawElements.length + 8000
      );
      return () => {
        clearTimeout(toSmallTimeOut);
        clearTimeout(goNextTimeOut);
      };
    }
    return () => {
      if (changeTitleTimeOut.current) clearTimeout(changeTitleTimeOut.current);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentElementIndex]);

  // if (!storedPhoto) {
  //   return <Title variant="h4">Upload your photo</Title>;
  // }

  // console.log(shouldDisplayPalmLines);
  // return <Title variant="h4">Upload your photo</Title>;

  return (
    <>
      <h2
        className="palmistry-container__title"
        style={{
          animationDelay: `${drawElementChangeDelay * drawElements.length}ms`,
          animationDuration: `${drawElementChangeDelay}ms`,
        }}
      >
        {title}
      </h2>
      <ScannedPhoto
        photo={storedPhoto}
        small={smallPhotoState}
        drawElementChangeDelay={drawElementChangeDelay}
        startDelay={startDelay}
        displayLines={shouldDisplayPalmLines}
        lines={lines}
        fingers={fingers}
        drawElements={drawElements}
      />

      <h2
        className="palmistry-container__waiting-title"
        style={{
          animationDelay: `${
            drawElementChangeDelay * drawElements.length + 2500
          }ms`,
        }}
      >
        {translate("/scan-photo.title")}
      </h2>

      <h3
        className="palmistry-container__waiting-description"
        style={{
          animationDelay: `${
            drawElementChangeDelay * drawElements.length + 3000
          }ms`,
        }}
      >
        {translate("/scan-photo.text")}
      </h3>
    </>
  );
}
