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 LoadingProfileModalChild from "@/components/LoadingProfileModalChild";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import { EUserDeviceType } from "@/store/userConfig";

function LoadingProfilePage() {
  const userDeviceType = useSelector(selectors.selectUserDeviceType);
  const isShowTryApp = useSelector(selectors.selectIsShowTryApp);

  const navigate = useNavigate();
  const [progress, setProgress] = useState(0);
  const [isPause, setIsPause] = useState(false);
  const interval = useRef<NodeJS.Timeout>();

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

  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]);

  return (
    <section className={`${styles.page} page`}>
      {isPause && (
        <Modal open={!!isPause} onClose={() => setIsPause(false)}>
          <LoadingProfileModalChild
            title={modalTitlesLoadingProfile[Math.floor(progress / 100)]}
            handleClick={() => setIsPause(false)}
          />
        </Modal>
      )}
      <Title variant="h1" className={styles.title}>
        {titlesLoadingProfile[Math.floor(progress / 34)]}
      </Title>
      <div className={styles["points-container"]}>
        {loadingProfilePoints.map(({ title, color }, index) => (
          <div
            className={`${styles["point"]} ${styles[color]}`}
            key={`point-${index}`}
          >
            <div className={styles["point__text-container"]}>
              <Title
                variant="h2"
                className={styles["point__title"]}
                style={{ color }}
              >
                {title}
              </Title>
              <p className={styles["point__percentage"]} style={{ color }}>
                {getProgressValue(index)}%
              </p>
            </div>
            <ProgressBarLine
              containerClassName={styles["progress-bar__container"]}
              lineClassName={styles["progress-bar__line"]}
              lineColor={color}
              value={getProgressValue(index)}
              delay={50}
            />
          </div>
        ))}
      </div>
      <p className={styles.description}>
        Sit tight! We`re building your perfect guidance plane based on your
        unique astrological blueprint and data of millions users.
      </p>
    </section>
  );
}

export default LoadingProfilePage;
