import { useEffect, useState } from "react";
import Title from "../Title";
import ProgressBarLine from "../ui/ProgressBarLine";
import styles from "./styles.module.css";
import Spinner from "../ui/Spinner";
import { useSelector } from "react-redux";
import { selectors } from "@/store";

interface ICompatibilityLoadingProps {
  secondPerson: string;
  onEndLoading: () => void;
}

const progressBars = [
  {
    label: "Analysis of me",
  },
  {
    label: "Analysis of the second person",
  },
  {
    label: "General compatibility",
  },
  {
    label: "Identifying compatibility issues",
  },
];

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

function CompatibilityLoading({secondPerson, onEndLoading}: ICompatibilityLoadingProps): JSX.Element {
  const [progress, setProgress] = useState(0);
  const homeConfig = useSelector(selectors.selectHome);
  const showNavbarFooter = homeConfig.isShowNavbar;

  useEffect(() => {
    if (progress >= progressBars.length * 100) {
      return onEndLoading()
    }
    const interval = setTimeout(() => {
      setProgress((prevProgress) => {
        return prevProgress + 1;
      });
    }, 50);
    return () => {
      clearTimeout(interval);
    }
  }, [progress, onEndLoading]);

  return (
    <section className={`${styles.container}`} style={{ paddingBottom: showNavbarFooter ? '48px' : '16px'}}>
      <Title variant="h3" className={styles.title}>
        Analysis of you with {secondPerson}
      </Title>
      {progressBars.map((progressBar, index) => (
        <div className={styles["progress-bar"]} key={index}>
          <Title variant="h4" className={styles["progress-bar__label"]}>
            {progressBar.label}
          </Title>
          <div className={styles["progress-bar__container"]}>
            <ProgressBarLine containerClassName={styles["progress-bar__line"]} value={getProgressValue(index, progress)} delay={50} />
            <span className={styles["progress-bar__percentage"]}>
              {getProgressValue(index, progress)}%
            </span>
          </div>
        </div>
      ))}
      <Spinner width="40px" strokeWidth={3} />
    </section>
  );
}

export default CompatibilityLoading;
