import styles from "./styles.module.scss";
import { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { useNavigate, useOutletContext } from "react-router-dom";
import routes from "@/routes";
import EmailsList from "@/components/EmailsList";
import Header from "../../components/Header";
import BackgroundTopBlob from "../../ui/BackgroundTopBlob";
import { useDynamicSize } from "@/hooks/useDynamicSize";
import PriceList from "../../components/PriceList";
import QuestionnaireGreenButton from "../../ui/GreenButton";
import { getRandomArbitrary } from "@/services/random-value";
import Loader from "@/components/Loader";
import metricService, {
  EGoals,
  EMetrics,
  useMetricABFlags,
} from "@/services/metric/metricService";
import Toast from "../../components/Toast";
import BlurComponent from "@/components/BlurComponent";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";
import DiscountExpires from "../TrialPayment/components/DiscountExpires";
import { IOutletContext } from "@/routerComponents/ABDesign/v1/LayoutABDesignV1";
import { useFunnel } from "@/hooks/funnel/useFunnel";

enum EDisplayOptionButton {
  "alwaysVisible" = "alwaysVisible",
  "visibleIfChosen" = "visibleIfChosen",
}

const displayOptionButton: EDisplayOptionButton =
  EDisplayOptionButton.alwaysVisible; //

function TrialChoiceVideoPage() {
  const { translate } = useTranslations(ELocalesPlacement.V1);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const selectedPrice = useSelector(selectors.selectSelectedPrice);
  const homeConfig = useSelector(selectors.selectHome);
  const email = useSelector(selectors.selectEmail);
  const [isDisabled, setIsDisabled] = useState(true);
  const [visibleToast, setVisibleToast] = useState(false);
  const [countUsers, setCountUsers] = useState(752);
  const { width: pageWidth, elementRef: pageRef } = useDynamicSize({});
  const { gender } = useSelector(selectors.selectQuestionnaire);
  const { products, isPending, currency } = useFunnel({
    funnel: ELocalesPlacement.V1,
    paymentPlacement: "main"
  });
  const arrowLeft = useSelector(selectors.selectTrialChoiceArrowOptions)?.left;
  const containerVideoRef = useRef<HTMLDivElement>(null);

  const { containerVideoRef: videoRef, isVisibleElements } =
    useOutletContext<IOutletContext>();

  const { flags } = useMetricABFlags();
  const isShowTimer = flags?.showTimerTrial?.[0] === "show";

  const { videoUrl } = useSelector(selectors.selectPersonalVideo);

  useEffect(() => {
    dispatch(actions.personalVideo.updateIsVideoPlaying(true));
  }, [dispatch]);

  useEffect(() => {
    metricService.reachGoal(EGoals.AURA_TRIAL_CHOICE_PAGE_VISIT, [
      EMetrics.KLAVIYO,
    ]);
  }, []);

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

  const handlePriceItem = () => {
    metricService.reachGoal(EGoals.AURA_SELECT_TRIAL, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
    setIsDisabled(false);
  };

  const handleNext = () => {
    if (isDisabled) {
      setVisibleToast(true);
      return;
    }
    dispatch(
      actions.siteConfig.update({
        home: { pathFromHome: homeConfig.pathFromHome, isShowNavbar: false },
      })
    );
    navigate(routes.client.trialPaymentV1());
  };

  useEffect(() => {
    if (!visibleToast) return;
    const timeOut = setTimeout(() => {
      setVisibleToast(false);
    }, 6000);
    return () => clearTimeout(timeOut);
  }, [visibleToast]);

  useEffect(() => {
    if (!containerVideoRef.current || !videoRef.current) return;
    containerVideoRef.current?.appendChild(videoRef.current);
    videoRef.current.classList.add(styles["personal-video"]);
  }, [videoRef]);

  return (
    <section
      className={`${styles.page} page`}
      ref={pageRef}
      style={{
        backgroundColor: gender === "male" ? "#C1E5FF" : "#f7ebff",
        paddingTop: !videoUrl.length ? "15px" : "0px",
      }}
    >
      <BackgroundTopBlob
        width={pageWidth}
        className={styles["background-top-blob"]}
        height={180}
      />
      <Header className={styles.header} />
      <div ref={containerVideoRef} />
      {/* <PersonalVideo
        gender={gender}
        url={"/trial-choice.MOV"}
        classNameContainer={styles["personal-video"]}
        isVisibleControllers={isVisibleElements}
        onVideoStart={showElements}
      /> */}
      {/* {containerVideoRef.current?.ELEMENT_NODE} */}
      {!isPending && isVisibleElements && (
        <>
          {isShowTimer && (
            <DiscountExpires
              className={styles["discount-expires"]}
              style={{
                marginTop: !videoUrl.length
                  ? "60px"
                  : "calc((100% + 84px) / 16* 9 + 16px)",
              }}
            />
          )}

          <div className={styles["price-container"]}>
            <PriceList
              products={products}
              activeItem={selectedPrice}
              classNameItem={styles["price-item"]}
              classNameItemActive={`${styles["price-item-active"]} ${styles[gender]}`}
              currency={currency}
              click={handlePriceItem}
            />
            <p
              className={styles["auxiliary-text"]}
              style={{
                maxWidth: arrowLeft
                  ? `${Number(arrowLeft.slice(0, -2)) - 8}px`
                  : "75%",
              }}
            >
              {/* {getText("text.3", {
                color: "#1C38EA",
              })} */}
            </p>
            <img
              className={styles["arrow-image"]}
              src="/arrow.svg"
              alt={`Arrow to $${products.at(-1)?.trialPrice}`}
              style={
                arrowLeft
                  ? {
                    left: arrowLeft,
                  }
                  : {}
              }
            />
          </div>
          <div className={styles["emails-list-container"]}>
            <EmailsList
              // title={getText("text.5", {
              //   replacementSelector: "strong",
              //   replacement: [
              //     {
              //       target: "${quantity}",
              //       replacement: countUsers.toString(),
              //     },
              //   ],
              // })}
              title={""}
              products={products}
              classNameContainer={`${styles["emails-container"]} ${styles[gender]}`}
              classNameTitle={styles["emails-title"]}
              classNameEmailItem={styles["email-item"]}
              direction="right-left"
              currency={currency}
            />
          </div>
          <p className={styles.email}>{email}</p>
          {!isDisabled &&
            displayOptionButton === EDisplayOptionButton.visibleIfChosen && (
              <QuestionnaireGreenButton
                className={styles.button}
                disabled={isDisabled}
                onClick={handleNext}
              >
                {/* {getText("text.button.1", {
                  color: "#1C38EA",
                })} */}
              </QuestionnaireGreenButton>
            )}
          {displayOptionButton === EDisplayOptionButton.alwaysVisible && (
            <BlurComponent
              className={styles.blur}
              gradientClassName={styles["gradient-blur"]}
              isActiveBlur={true}
            >
              <QuestionnaireGreenButton
                className={`${styles.button} ${isDisabled ? styles.disabled : ""
                  }`}
                onClick={handleNext}
              >
                {/* {getText("text.button.1", {
                  color: "#1C38EA",
                })} */}
              </QuestionnaireGreenButton>
            </BlurComponent>
          )}
          <p className={styles["auxiliary-text"]}>
            {/* {getText("text.4", {
              color: "#1C38EA",
            })} */}
          </p>
        </>
      )}
      {visibleToast && isDisabled && (
        <Toast classNameContainer={styles["toast-container"]} variant="error">
          {translate("/trial-choice.button")}
          {/* Choose an amount that you think is reasonable. */}
        </Toast>
      )}
      {isPending && <Loader className={styles.loader} />}
    </section>
  );
}

export default TrialChoiceVideoPage;
