import Title from "@/components/Title";
import styles from "./styles.module.css";
import ProgressBarLine from "@/components/ui/ProgressBarLine";
import {
  loadingProfilePoints,
  modalTitlesLoadingProfile,
  titlesLoadingProfile,
} from "@/data/loadingProfile";
import { useCallback, useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import Modal from "@/components/Modal";
// import { useSelector } from "react-redux";
// import { selectors } from "@/store";
// import { EUserDeviceType } from "@/store/userConfig";
import Header from "../../components/Header";
import { useDynamicSize } from "@/hooks/useDynamicSize";
import BackgroundTopBlob from "../../ui/BackgroundTopBlob";
import LoadingProfileModalChild from "../../components/LoadingProfileModalChild";
import ProgressBarSubstrate from "./ProgressBarSubstrate";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";
import { useMetricABFlags } from "@/services/metric/metricService";
import { EUnleashFlags, useUnleash } from "@/hooks/ab/unleash/useUnleash";
import { useAuthentication } from "@/hooks/authentication/use-authentication";
import { ESourceAuthorization } from "@/api/resources/User";
import { useSelector } from "react-redux";
import { selectors } from "@/store";

function LoadingProfilePage() {
  // const userDeviceType = useSelector(selectors.selectUserDeviceType);
  // const isShowTryApp = useSelector(selectors.selectIsShowTryApp);
  const { width: pageWidth, elementRef: pageElement } = useDynamicSize({});
  const { authorization } = useAuthentication();

  const navigate = useNavigate();
  const { translate } = useTranslations(ELocalesPlacement.V1);
  const [progress, setProgress] = useState(0);
  const [isPause, setIsPause] = useState(false);
  const interval = useRef<NodeJS.Timeout>();
  const pointsRef = useRef<HTMLDivElement[]>([]);
  const { flags } = useMetricABFlags();
  const { variant: emailEnterVariant } = useUnleash({
    flag: EUnleashFlags.compatibilityV1EmailEnter,
  });
  const feature = useSelector(selectors.selectFeature);
  const isHideEmailByFeature = feature?.includes("ios/link") ?? false;

  useEffect(() => {
    if (emailEnterVariant === "hide" || isHideEmailByFeature) {
      (async () => {
        await authorization("", ESourceAuthorization["aura.main.new"], true);
      })();
    }
  }, [emailEnterVariant, isHideEmailByFeature]);

  const onEndLoading = useCallback(() => {
    // if (isShowTryApp && userDeviceType === EUserDeviceType.ios) {
    //   return navigate(routes.client.tryApp());
    // }

    if (flags?.auraPalmistry?.[0] === "on") {
      return navigate(routes.client.findHappinessV1());
    }
    if (emailEnterVariant === "hide" || isHideEmailByFeature) {
      return navigate(routes.client.tryAppV1());
    }
    return navigate(routes.client.emailEnterV1());
  }, [flags?.auraPalmistry, navigate, emailEnterVariant, isHideEmailByFeature]);

  const getProgressValue = useCallback(
    (index: number) => {
      const integerDivision = Math.floor(progress / 100);
      if (integerDivision > index) {
        return 100;
      }
      if (integerDivision === index) {
        return progress % 100;
      }
      return 0;
    },
    [progress]
  );

  useEffect(() => {
    if (progress % 98 === 97) {
      setIsPause(true);
    }
  }, [progress]);

  useEffect(() => {
    if (progress >= loadingProfilePoints.length * 100) {
      return onEndLoading();
    }
    interval.current = setTimeout(() => {
      setProgress((prevProgress) => {
        if (!isPause) return prevProgress + 1;
        return prevProgress;
      });
    }, 100);
    return () => {
      clearTimeout(interval.current);
    };
  }, [progress, onEndLoading, isPause]);

  const getCurrentIndex = () => {
    return Math.floor(progress / 100);
  };

  return (
    <section className={`${styles.page} page`} ref={pageElement}>
      {isPause && (
        <Modal
          isCloseButtonVisible={false}
          open={!!isPause}
          onClose={() => setIsPause(false)}
          className={styles.modal}
          containerClassName={styles["modal-container"]}
        >
          <LoadingProfileModalChild
            title={translate(modalTitlesLoadingProfile[getCurrentIndex()])}
            handleClick={() => setIsPause(false)}
          />
        </Modal>
      )}
      <BackgroundTopBlob
        className={styles["background-top-blob"]}
        width={pageWidth}
        height={180}
      />
      <Header className={styles["header"]} />

      <Title variant="h1" className={styles.title}>
        {translate(titlesLoadingProfile[Math.floor(progress / 34)])}
      </Title>
      <div className={styles["points-container"]}>
        {loadingProfilePoints.map(({ title, color }, index) => (
          <div
            className={`${styles["point"]} ${getCurrentIndex() === index && styles["active"]
              }`}
            ref={(el) => (pointsRef.current[index] = el as HTMLDivElement)}
            key={`point-${index}`}
          >
            <div className={styles["point__text-container"]}>
              <Title variant="h2" className={styles["point__title"]}>
                {translate(title)}
              </Title>
              <p
                className={styles["point__percentage"]}
                style={{
                  color: getProgressValue(index) === 100 ? "#1c1c1c" : "#fff",
                }}
              >
                {getProgressValue(index)}%
              </p>
            </div>
            <ProgressBarLine
              containerClassName={styles["progress-bar__container"]}
              lineClassName={styles["progress-bar__line"]}
              lineColor={color}
              value={getProgressValue(index)}
              delay={50}
            />
            {getCurrentIndex() === index && (
              <ProgressBarSubstrate
                className={styles["progress-bar__substrate"]}
                width={pageWidth - 32}
                style={{
                  top: pointsRef.current[index]?.offsetTop - 64 || 0,
                  left: 0,
                }}
              />
            )}
          </div>
        ))}
      </div>
      <p className={styles.description}>
        {translate("/loading-profile.description")}
      </p>
    </section>
  );
}

export default LoadingProfilePage;
