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 IProgressBarsModalProps {
  children: JSX.Element[];
  progressBars: ProgressBar[];
  className?: string;
  onEndLoading: () => void;
}

export interface ProgressBar {
  label: string;
}

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 ProgressBarsModal({
  progressBars,
  className,
  onEndLoading,
  children,
}: React.PropsWithChildren<IProgressBarsModalProps>): 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} ${className || ""}`}
      style={{ paddingBottom: showNavbarFooter ? "48px" : "16px" }}
    >
      <div className={styles.title}>{children[0]}</div>
      {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 ProgressBarsModal;
