import Title from "@/components/Title";
import styles from "./styles.module.scss";
import { useCallback, useEffect, useRef, useState } from "react";
import routes, { emailMarketingV1Prefix, palmistryV2Prefix } from "@/routes";
import { useNavigate, useSearchParams } from "react-router-dom";
import { onboardingTitles } from "../../data/onboarding";
import ProgressBarLine from "@/components/ui/ProgressBarLine";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys } from "@/api/resources/Paywall";
import { usePersonalVideo } from "@/hooks/personalVideo/usePersonalVideo";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import metricService, {
  EGoals,
  EMetrics,
  useMetricABFlags,
} from "@/services/metric/metricService";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";
import QuestionnaireGreenButton from "../../ui/GreenButton";

function OnboardingPage() {
  const { translate } = useTranslations(ELocalesPlacement.V1);
  const navigate = useNavigate();
  const [activeIndexTitle, setIndexTitle] = useState(0);
  const [periodClassName, setPeriodClassName] = useState("");
  const titleInterval = useRef<NodeJS.Timeout>();
  const classNameTimeOut = useRef<NodeJS.Timeout>();
  const [progress, setProgress] = useState(0);
  const [isLoadingEnd, setIsLoadingEnd] = useState(false);
  const progressInterval = useRef<NodeJS.Timeout>();
  usePaywall({
    placementKey: EPlacementKeys["aura.placement.redesign.main"],
    localesPlacement: ELocalesPlacement.V1,
  });
  const { isVideoReady } = usePersonalVideo();
  const { createdDate, generatingVideo } = useSelector(
    selectors.selectPersonalVideo
  );
  const authCode = useSelector(selectors.selectAuthCode);
  const { flags } = useMetricABFlags();
  const auraVideoTrial = flags?.auraVideoTrial?.[0];

  const [searchParams] = useSearchParams();
  const path = searchParams.get("path");

  const handleNext = useCallback(() => {
    if (path === "compatibility") {
      return navigate(routes.client.home());
    }
    if (path === "palmistry") {
      return navigate(routes.client.home());
    }
    if (window.location.pathname.includes(emailMarketingV1Prefix)) {
      return navigate(routes.client.home());
    }
    if (window.location.pathname.includes(palmistryV2Prefix)) {
      return navigate(routes.client.home());
    }
    if (auraVideoTrial === "on") {
      return navigate(routes.client.trialChoiceVideoV1());
    }
    // if (authCode?.length) {
      return navigate(routes.client.tryAppV1());
    // }
    return navigate(routes.client.trialChoiceV1());
  }, [auraVideoTrial, authCode?.length, navigate, path]);

  useEffect(() => {
    if (isVideoReady && progress >= 100) {
      if (auraVideoTrial === "on") {
        return setIsLoadingEnd(true);
      }
      return handleNext();
    }
  }, [activeIndexTitle, auraVideoTrial, handleNext, isVideoReady, progress]);

  useEffect(() => {
    setPeriodClassName("to-nontransparent");
    if (activeIndexTitle < onboardingTitles.length - 1) {
      classNameTimeOut.current = setTimeout(() => {
        setPeriodClassName("to-transparent");
      }, 4000);
    }
    titleInterval.current = setTimeout(() => {
      if (activeIndexTitle < onboardingTitles.length - 1) {
        setIndexTitle((prev) => prev + 1);
      }
    }, 5000);
    return () => {
      if (titleInterval.current) clearTimeout(titleInterval.current);
      if (classNameTimeOut.current) clearTimeout(classNameTimeOut.current);
    };
  }, [activeIndexTitle, handleNext]);

  const getProgressIntervalTiming = useCallback(() => {
    const generateTimeLimit = import.meta.env.AURA_PERSONAL_VIDEO_TIME_LIMIT;
    const baseTiming = (onboardingTitles.length * 5000) / 100;
    const generatingVideoTiming =
      (Number(generateTimeLimit) * 1000 - new Date().getTime() + createdDate) /
      30;
    if (progress < 70 || isVideoReady) return baseTiming;
    return generatingVideoTiming < baseTiming
      ? baseTiming
      : generatingVideoTiming;
  }, [createdDate, isVideoReady, progress]);

  useEffect(() => {
    progressInterval.current = setInterval(() => {
      setProgress((prev) => {
        if (prev === 99 && generatingVideo) {
          metricService.reachGoal(EGoals.ROSE_LOADING_END, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
        };
        if (prev >= 100) return prev;
        return prev + 1;
      });
    }, getProgressIntervalTiming());
    return () => {
      if (progressInterval.current) clearInterval(progressInterval.current);
    };
  }, [generatingVideo, getProgressIntervalTiming]);

  useEffect(() => {
    metricService.reachGoal(EGoals.ROSE_LOADING_START, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
  }, []);

  return (
    <section className={`${styles.page} page`}>
      <img
        className={`${styles.image} ${styles[periodClassName]}`}
        src="/leo.webp"
        alt="Leo"
      />
      {onboardingTitles[activeIndexTitle] && (
        <Title className={`${styles.title} ${styles[periodClassName]}`}>
          {translate(onboardingTitles[activeIndexTitle])}
        </Title>
      )}
      <footer className={styles.footer}>
        <div
          className={`${styles["progress-bar__text-container"]} ${isLoadingEnd && styles.hide
            }`}
        >
          <Title variant="h2" className={styles["progress-bar__title"]}>
            {translate("/onboarding.loader_title")}
          </Title>
          <p className={styles["progress-bar__percentage"]}>{progress}%</p>
        </div>
        <ProgressBarLine
          containerClassName={`${styles["progress-bar__container"]} ${isLoadingEnd && styles.hide
            }`}
          lineClassName={styles["progress-bar__line"]}
          lineColor={"#3750A8"}
          value={progress}
          delay={(onboardingTitles.length * 5000) / 100}
        />
        {isLoadingEnd && (
          <QuestionnaireGreenButton
            className={styles.button}
            onClick={handleNext}
          >
            Next
          </QuestionnaireGreenButton>
        )}
      </footer>
    </section>
  );
}

export default OnboardingPage;
