import { useSelector } from "react-redux";
import styles from "./styles.module.scss";
import { selectors } from "@/store";
import { useEffect, useMemo, useRef, useState } from "react";
import { IPalmistryLine } from "@/api/resources/Palmistry";
import Title from "@/components/Title";
import { IPalmistryFingerLocal } from "@/store/palmistry";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import ScannedPhotoElement from "@/components/palmistry/scanned-photo/scanned-photo";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";
import { useAuthentication } from "@/hooks/authentication/use-authentication";
import { ESourceAuthorization } from "@/api/resources/User";
import { usePreloadImages } from "@/hooks/preload/images";

const drawElementChangeDelay = 1500;
const startDelay = 500;

function ScannedPhoto() {
  const { translate } = useTranslations(ELocalesPlacement.PalmistryV1);
  const navigate = useNavigate();
  const photo = useSelector(selectors.selectPalmistryPhoto);
  const fingers = useSelector(selectors.selectPalmistryFingers);
  const lines = useSelector(selectors.selectPalmistryLines);

  const changeTitleTimeOut = useRef<NodeJS.Timeout>();

  const [currentElementIndex, setCurrentElementIndex] = useState(0);
  const [title, setTitle] = useState("");
  const [shouldDisplayPalmLines, setShouldDisplayPalmLines] = useState(false);
  const [smallPhotoState, setSmallPhotoState] = useState(false);

  const feature = useSelector(selectors.selectFeature);
  const isIOSPath = useMemo(() => feature?.toLowerCase()?.includes("black") || feature?.toLowerCase()?.includes("ios"), [feature]);
  const authCode = useSelector(selectors.selectAuthCode);

  const { authorization } = useAuthentication();

  usePreloadImages([
    "/v2/palmistry/download-app.png",
    "/v1/palmistry/love-line.svg",
    "/v1/palmistry/head-line.svg",
    "/v1/palmistry/life-line.svg",
    "/v1/palmistry/fate-line.svg",
    "/v1/palmistry/hand-little-finger.svg",
    "/v1/palmistry/partners.png"
  ])


  useEffect(() => {
    if (isIOSPath) {
      (async () => {
        await authorization("", ESourceAuthorization["aura.palmistry.new"], true);
      })();
    }
  }, [isIOSPath, authorization])


  const drawElements = useMemo(() => [...fingers, ...lines], [fingers, lines]);

  useEffect(() => {
    if (!drawElements[currentElementIndex]) return;
    changeTitleTimeOut.current = setTimeout(() => {
      const title =
        (drawElements[currentElementIndex] as IPalmistryFingerLocal)
          .fingerName || drawElements[currentElementIndex].name;
      setTitle(title);
      if (currentElementIndex < drawElements.length - 1) {
        setCurrentElementIndex((prevState) => prevState + 1);
      }
    }, drawElementChangeDelay);

    return () => {
      if (changeTitleTimeOut.current) {
        clearTimeout(changeTitleTimeOut.current);
      }
    };
  }, [currentElementIndex, drawElements]);

  useEffect(() => {
    setShouldDisplayPalmLines(
      lines.includes(drawElements[currentElementIndex] as IPalmistryLine)
    );
  }, [currentElementIndex, drawElements, lines]);

  useEffect(() => {
    if (currentElementIndex < drawElements.length - 1) return;
    const timer = setTimeout(() => {
      setSmallPhotoState(true);
    }, drawElementChangeDelay * 2);
    const goNextTimer = setTimeout(
      () => {
        handleNext()
      },
      drawElementChangeDelay * drawElements.length + 8000
    );

    return () => {
      if (timer) {
        clearTimeout(timer);
      }
      if (goNextTimer) {
        clearTimeout(goNextTimer);
      }
    };
  }, [currentElementIndex, drawElements.length]);

  const handleNext = () => {
    const isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
    if (isIOSPath && !!authCode && isIOS) {
      return navigate(routes.client.palmistryV1TryApp());
    }
    return navigate(routes.client.palmistryV1Email())
  }

  // useEffect(() => {
  //   if (currentElementIndex < drawElements.length) return;
  //   const timer = setTimeout(() => {
  //     // navigate(routes.client.palmistryV1Email());
  //   }, drawElementChangeDelay + 1000);
  //   return () => clearTimeout(timer);
  // }, [currentElementIndex, drawElements.length, navigate]);

  useEffect(() => {
    if (currentElementIndex < drawElements.length - 1) return;

    const timer = setTimeout(() => {
      setTitle("");
    }, drawElementChangeDelay * 2)

    return () => {
      if (timer) {
        clearTimeout(timer);
      }
    }
  }, [currentElementIndex, drawElements])

  return (
    <section className={`${styles.page} palmistry-container_type_scan-photo`}>
      <Title variant="h2" className={styles.title}>
        {title}
      </Title>
      <ScannedPhotoElement
        photo={photo}
        small={smallPhotoState}
        drawElementChangeDelay={drawElementChangeDelay}
        startDelay={startDelay}
        displayLines={shouldDisplayPalmLines}
        lines={lines.map((line) => ({
          ...line,
          label: translate(`/scanned-photo.palm_lines.${line.name}`)
        }))}
        fingers={fingers}
        drawElements={drawElements}
      />
      <h2
        className={`palmistry-container__waiting-title ${styles.waitingTitle}`}
        style={{
          animationDelay: `${drawElementChangeDelay * drawElements.length + 2500
            }ms`,
        }}
      >
        {translate("/scanned-photo.title")}
      </h2>

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

export default ScannedPhoto;
