import { useDispatch, useSelector } from "react-redux";
import EmailSubstrate from "../../components/EmailSubstrate";
import styles from "./styles.module.scss";
import { actions, selectors } from "@/store";
// import Title from "@/components/Title";
import PriceList from "@/components/pages/ABDesign/v1/components/PriceList";
import { addCurrency, ELocalesPlacement } from "@/locales";
import { useEffect, useMemo, useState } from "react";
import Button from "../../components/Button";
import routes from "@/routes";
import { useNavigate } from "react-router-dom";
import Loader from "@/components/Loader";
import { useTranslations } from "@/hooks/translations";
// import { useMetricABFlags } from "@/services/metric/metricService";
import metricService, { EGoals, EMetrics, useMetricABFlags } from "@/services/metric/metricService";
import TrialChoiceV1 from "./v1";
import { usePreloadImages } from "@/hooks/preload/images";
import { EUnleashFlags, useUnleash } from "@/hooks/ab/unleash/useUnleash";
import { getFormattedPrice } from "@/utils/price.utils.tsx";
import { useFunnel } from "@/hooks/funnel/useFunnel";

function TrialChoice() {
  const { translate, getPeriodText } = useTranslations(ELocalesPlacement.PalmistryV1);
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const {
    isPending,
    products,
    currency,
    trialInterval,
    trialPeriod,
    getProperty
  } = useFunnel({
    funnel: ELocalesPlacement.PalmistryV1,
    paymentPlacement: "main"
  })

  usePreloadImages([
    "/v1/palmistry/trial-payment/girl2.png",
    "/v1/palmistry/trial-payment/avatar-1.png",
    "/v1/palmistry/trial-payment/avatar-2.png",
    "/v1/palmistry/trial-payment/avatar-3.png",
    "/v1/palmistry/trial-payment/avatar-4.png",
    "/v1/palmistry/love-line.svg",
    "/v1/palmistry/head-line.svg",
    "/v1/palmistry/life-line.svg",
    "/v1/palmistry/fate-line.svg",
    "/v1/palmistry/hand-little-finger.svg",
    "/v1/palmistry/partners.png"
  ])

  const { flags, ready } = useMetricABFlags();
  const trialChoicePageType = flags?.trialChoicePageType?.[0];
  // const trialChoicePageType = "v1";
  // const isLongText = flags?.text?.[0] === "on";

  const [isDisabled, setIsDisabled] = useState(true);

  const selectedPrice = useSelector(selectors.selectSelectedPrice);
  const email = useSelector(selectors.selectEmail);
  const homeConfig = useSelector(selectors.selectHome);
  const maxProduct = useMemo(() => {
    if (!products?.length) return null;
    return products.reduce(
      (max, product) => {
        return Number(product.trialPrice || 0) > Number(max.trialPrice || 0) ? product : max
      },
      products[0]
    );
  }, [products]);

  const maxTrialPrice = useMemo(() => {
    if (!maxProduct) return "";
    return addCurrency(
      getFormattedPrice(maxProduct.trialPrice || 0),
      currency
    );
  }, [maxProduct, currency]);
  const { variant: trialPriceVariant = 'v0', isReady: isReadyTrialPrice } = useUnleash({
    flag: EUnleashFlags.palmistryV1TrialTextPrice,
  });

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

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

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

  if (!ready || !isReadyTrialPrice) {
    return (
      <div className={styles.container}>
        <Loader className={styles.loader} />
      </div>
    );
  }

  if (trialChoicePageType === "v1") {
    return <TrialChoiceV1 />;
  }

  let trialPriceTextVariant = 'v0';
  switch (trialPriceVariant) {
    case "v0":
      trialPriceTextVariant = "v0";
      break;
    case "v1":
      trialPriceTextVariant = "v1";
      break;
    case "v2":
      trialPriceTextVariant = "v2";
      break;
    case "v3":
      trialPriceTextVariant = "v3";
      break;
    default:
      trialPriceTextVariant = "v0";
      break;
  }

  return (
    <div className={styles.container}>
      {!(isPending || !isReadyTrialPrice || !maxProduct) && (
        <>
          <EmailSubstrate className={styles["email-substrate"]} email={email} />
          {/* {!isLongText && (
            <Title className={styles.title} variant="h2">
              {getText("text.0")}
            </Title>
          )} */}
          <p className={styles.text}>{
            translate('/trial-choice.description', {
              maxTrialPrice,
              trialPeriod1: getPeriodText(trialPeriod, trialInterval || 0),
              trialPeriod2: getPeriodText(trialPeriod, trialInterval || 0),
              br: <br />
            })
          }</p>

          <div className={styles["price-container"]}>
            <PriceList
              products={products}
              activeItem={selectedPrice}
              classNameItem={styles["price-item"]}
              classNameItemActive={`${styles["price-item-active"]}`}
              classNamePricesContainer={styles["prices-container"]}
              currency={currency}
              click={handlePriceItem}
            />
            <p className={styles["auxiliary-text"]}>
              {translate(`${getProperty("text.1")?.value}.${trialPriceTextVariant}`, {
                price: maxTrialPrice,
                br: <br />
              })}
            </p>
          </div>

          <Button
            className={styles.button}
            disabled={isDisabled}
            onClick={handleNext}
          >
            {translate("next")}
          </Button>
        </>
      )}
      {(isPending || !isReadyTrialPrice) && <Loader className={styles.loader} />}
    </div>
  );
}

export default TrialChoice;
