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 } from "@/services/metric/metricService";
import { usePreloadImages } from "@/hooks/preload/images";
import { getZodiacSignByDate } from "@/services/zodiac-sign";
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.CompatibilityV4);
  const navigate = useNavigate();
  const dispatch = useDispatch();

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

  const { gender, partnerGender, birthdate, partnerBirthdate } = useSelector(selectors.selectQuestionnaire)
  const zodiacSign = getZodiacSignByDate(birthdate);
  const zodiacSignPartner = getZodiacSignByDate(partnerBirthdate);

  usePreloadImages([
    "/v4/compatibility/trial-payment/book.png",
    `/zodiac-signs/${gender?.toLowerCase()}/${zodiacSign?.toLowerCase()}.svg`,
    `/zodiac-signs/${partnerGender?.toLowerCase()}/${zodiacSignPartner?.toLowerCase()}.svg`,
    "/v4/compatibility/partners.png"
  ])

  // const { flags } = useMetricABFlags();
  // 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 = products.reduce((max, product) => {
  //   return Number(product.trialPrice) > Number(max.trialPrice) ? product : max
  // }, products[0])
  // const maxTrialPrice = addCurrency(
  //     getFormattedPrice(maxProduct?.trialPrice || 0),
  //     currency
  // );

  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.compatibilityV4TrialTextPrice,
  });

  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.compatibilityV4TrialPayment());
  };

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

  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;
