import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import styles from "./styles.module.css";
import UserHeader from "../UserHeader";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import Title from "../Title";
import { useTranslations } from "@/hooks/translations";
import EmailsList from "../EmailsList";
import PriceList from "../PriceList";
import { useEffect, useState } from "react";
import Loader from "../Loader";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys } from "@/api/resources/Paywall";
import { getRandomArbitrary } from "@/services/random-value";

function PriceListPage(): JSX.Element {
  const { translate } = useTranslations();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const homeConfig = useSelector(selectors.selectHome);
  const selectedPrice = useSelector(selectors.selectSelectedPrice);
  const email = useSelector(selectors.selectEmail);
  const { products, getText } = usePaywall({
    placementKey: EPlacementKeys["aura.placement.main"],
  });
  const [countUsers, setCountUsers] = useState(752);

  useEffect(() => {
    const randomDelay = getRandomArbitrary(3000, 5000);
    const countUsersTimeOut = setTimeout(() => {
      setCountUsers((prevState) => prevState + 1);
    }, randomDelay);
    return () => clearTimeout(countUsersTimeOut);
  }, [countUsers]);

  const handleNext = () => {
    dispatch(
      actions.siteConfig.update({
        home: { pathFromHome: homeConfig.pathFromHome, isShowNavbar: false },
      })
    );
    setTimeout(() => {
      navigate(routes.client.subscription());
    }, 1000);
  };

  return (
    <>
      <UserHeader email={email} />
      <section className={`${styles.page} page`}>
        {!!products.length && (
          <>
            <Title className={styles.title} variant="h2">
              {translate("choose_your_own_fee")}
            </Title>
            <p className={styles.slogan}>{translate("aura.web.price_selection")}</p>
            <div className={styles["emails-list-container"]}>
              <EmailsList
                title={getText("text.5", {
                  replacementSelector: "strong",
                  replacement: {
                    target: "${quantity}",
                    replacement: countUsers.toString(),
                  },
                })}
              />
            </div>
            <div className={styles["price-list-container"]}>
              <PriceList
                activeItem={selectedPrice}
                products={products}
                click={handleNext}
              />
            </div>
          </>
        )}
        {!products.length && <Loader />}
      </section>
    </>
  );
}

export default PriceListPage;
