import styles from "./styles.module.scss";
import { useCallback, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { useNavigate } 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 PersonalVideo from "../TrialPayment/components/PersonalVideo";
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 { useFunnel } from "@/hooks/funnel/useFunnel";

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

const displayOptionButton: EDisplayOptionButton =
  EDisplayOptionButton.alwaysVisible; //

function TrialChoicePage() {
  const { translate } = useTranslations(ELocalesPlacement.V1);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const selectedPrice = useSelector(selectors.selectSelectedPrice);
  // const activeProduct = useSelector(selectors.selectActiveProduct);
  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, trialInterval } = useFunnel({
    funnel: ELocalesPlacement.V1,
    paymentPlacement: "main"
  });
  const arrowLeft = useSelector(selectors.selectTrialChoiceArrowOptions)?.left;

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

  const textVariants = [
    translate("/trial-choice.text_variant_1", {
      br: "\n",
      trialDuration: trialInterval || "7",
      span: <span className={`${styles.text} ${styles.bold} ${styles.blue}`}>
        {translate("/trial-choice.text_variant_1_span", {
          trialDuration: trialInterval || "7",
        })}
      </span>,
    }),
    translate("/trial-choice.text_variant_2", {
      br: "\n",
      trialDuration: trialInterval || "7",
      span: <span className={`${styles.text} ${styles.bold} ${styles.blue}`}>
        {translate("/trial-choice.text_variant_2_span", {
          trialDuration: trialInterval || "7",
        })}
      </span>,
    }),
    translate("/trial-choice.text_variant_3", {
      br: "\n",
      trialDuration: trialInterval || "7",
      span: <span className={`${styles.text} ${styles.bold} ${styles.blue}`}>
        {translate("/trial-choice.text_variant_3_span", {
          trialDuration: trialInterval || "7",
        })}
      </span>,
    }),
  ];

  const textVariant = Number(flags?.text?.[0]) || 2;

  // const getPrice = useCallback(
  //   (product: IFunnelPaymentVariant) => {
  //     if (!product?.trialPrice) {
  //       return addCurrency(0, currency);
  //     }
  //     if (product.trialPrice % 100 === 0) {
  //       return addCurrency(product.trialPrice / 100, currency);
  //     }
  //     return addCurrency(
  //       ((product.trialPrice || 0) / 100).toFixed(2),
  //       currency
  //     );
  //   },
  //   [currency]
  // );

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

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

  const getFirstParagraphMargin = useCallback(() => {
    if (isShowTimer) {
      return "12px";
    }
    if (videoUrl.length) {
      return "calc((100% + 84px) / 16* 9 + 16px)";
    }
    return "60px";
  }, [isShowTimer, videoUrl.length]);

  return (
    <section
      className={`${styles.page} page`}
      ref={pageRef}
      style={{
        backgroundColor: gender === "male" ? "#C1E5FF" : "#f7ebff",
        paddingTop: !videoUrl.length ? "15px" : "0px",
      }}
    >
      {!videoUrl.length && (
        <>
          <BackgroundTopBlob
            width={pageWidth}
            className={styles["background-top-blob"]}
            height={180}
          />
          <Header className={styles.header} />
        </>
      )}
      {!!videoUrl.length && (
        <PersonalVideo
          gender={gender}
          url={videoUrl}
          classNameContainer={styles["personal-video"]}
        />
      )}
      {!isPending && (
        <>
          {isShowTimer && (
            <DiscountExpires
              className={styles["discount-expires"]}
              style={{
                marginTop: !videoUrl.length
                  ? "60px"
                  : "calc((100% + 84px) / 16* 9 + 16px)",
              }}
            />
          )}
          {(!textVariant && (
            <>
              <p
                className={styles.text}
                style={{
                  marginTop: getFirstParagraphMargin(),
                }}
              >
                {/* {getText("text.0", {
                  replacementSelector: "b",
                  color: "#1C38EA",
                })} */}
              </p>
              <p className={`${styles.text} ${styles.bold}`}>
                {/* {getText("text.1", {
                  color: "#1C38EA",
                })} */}
              </p>
              <p className={`${styles.text} ${styles.bold} ${styles.blue}`}>
                {/* {getText("text.2", {
                  color: "#1C38EA",
                  replacement: [
                    {
                      target: "${maxTrialPrice}",
                      replacement: getPrice(
                        products[products.length - 1] || products[0]
                      ),
                    },
                    {
                      target: "${trialDuration}",
                      replacement:
                        activeProduct?.trialDuration?.toString() ||
                        products[0]?.trialDuration?.toString() ||
                        "3",
                    },
                  ],
                })} */}
              </p>
            </>
          ))}
          {!!textVariant && (
            <p
              className={styles.text}
              style={{
                marginTop: getFirstParagraphMargin(),
                textAlign: "left",
                whiteSpace: "pre-line",
              }}
            >
              {textVariants[textVariant - 1]}
            </p>
          )}

          <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 TrialChoicePage;
