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, useRef, 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 { 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.CompatibilityV2
  );
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const bottomRef = useRef<HTMLDivElement>(null);

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

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

  usePreloadImages([
    `/zodiac-signs/${gender}/${zodiacSign?.toLowerCase()}.svg`,
    `/zodiac-signs/${partnerGender}/${zodiacSignPartner?.toLowerCase()}.svg`,
    "/v2/compatibility/reviews.png",
    "/v2/compatibility/trial-payment/girl2.png",
    "/v2/compatibility/trial-payment/avatar-1.png",
    "/v2/compatibility/trial-payment/avatar-2.png",
    "/v2/compatibility/trial-payment/avatar-4.png",
    "/v2/compatibility/money-back.svg",
    "/v2/compatibility/love-line.svg",
    "/v2/compatibility/head-line.svg",
    "/v2/compatibility/life-line.svg",
    "/v2/compatibility/fate-line.svg",
    "/v2/compatibility/hand-little-finger.svg",
    "/v2/compatibility/partners.png",
  ]);

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

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

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

  const selectedPrice = useSelector(selectors.selectSelectedPrice);
  const email = useSelector(selectors.selectEmail);
  const homeConfig = useSelector(selectors.selectHome);

  const { variant: trialPriceVariant = "v0", isReady: isReadyTrialPrice } =
    useUnleash({
      flag: EUnleashFlags.compatibilityV2TrialTextPrice,
    });

  const { variant: trialButtonVariant = "v0", isReady: isReadyTrialButton } =
    useUnleash({
      flag: EUnleashFlags.compatibilityV2TrialButton,
    });

  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 handlePriceItem = () => {
    metricService.reachGoal(EGoals.SELECT_TRIAL, [
      EMetrics.YANDEX,
      EMetrics.KLAVIYO,
    ]);
    metricService.reachGoal(EGoals.AURA_SELECT_TRIAL, [EMetrics.KLAVIYO]);
    setIsDisabled(false);
  };

  const handleNext = () => {
    if (isDisabled && ["v1", "v2", "v3", "v4"].includes(trialButtonVariant)) {
      setIsDisabledButtonClicked(true);

      bottomRef.current?.scrollIntoView({
        behavior: "smooth",
        block: "end",
      });
      return;
    }
    if (isDisabled) {
      return;
    }
    dispatch(
      actions.siteConfig.update({
        home: { pathFromHome: homeConfig.pathFromHome, isShowNavbar: false },
      })
    );
    navigate(routes.client.compatibilityV2TrialPayment());
  };

  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 || !isReadyTrialButton) {
    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 ||
        !isReadyTrialButton
      ) && (
        <>
          <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"]}`}>
            <div
              className={`${styles.priceListContainer} ${
                isDisabledButtonClicked &&
                isDisabled &&
                ["v1", "v2"].includes(trialButtonVariant)
                  ? styles.priceListContainerDisabled
                  : ""
              }`}
            >
              {isDisabledButtonClicked &&
                isDisabled &&
                ["v1", "v2"].includes(trialButtonVariant) && (
                  <div className={styles.priceListContainerDisabledText}>
                    <svg
                      width="16"
                      height="16"
                      viewBox="0 0 16 16"
                      fill="none"
                      xmlns="http://www.w3.org/2000/svg"
                    >
                      <rect width="16" height="16" rx="8" fill="#EF4444" />
                      <path
                        d="M8.75 3C8.75 2.58516 8.41484 2.25 8 2.25C7.58516 2.25 7.25 2.58516 7.25 3V9C7.25 9.41484 7.58516 9.75 8 9.75C8.41484 9.75 8.75 9.41484 8.75 9V3ZM8 12.75C8.24864 12.75 8.4871 12.6512 8.66291 12.4754C8.83873 12.2996 8.9375 12.0611 8.9375 11.8125C8.9375 11.5639 8.83873 11.3254 8.66291 11.1496C8.4871 10.9738 8.24864 10.875 8 10.875C7.75136 10.875 7.5129 10.9738 7.33709 11.1496C7.16127 11.3254 7.0625 11.5639 7.0625 11.8125C7.0625 12.0611 7.16127 12.2996 7.33709 12.4754C7.5129 12.6512 7.75136 12.75 8 12.75Z"
                        fill="white"
                      />
                    </svg>

                    {translate("/trial-choice.please-select")}
                  </div>
                )}

              <PriceList
                products={products}
                activeItem={selectedPrice}
                classNameItem={`${styles["price-item"]} ${
                  styles[trialButtonVariant]
                } ${
                  isDisabledButtonClicked && isDisabled
                    ? styles.priceItemDisabled
                    : ""
                }`}
                classNameItemActive={`${styles["price-item-active"]}`}
                classNamePricesContainer={styles["prices-container"]}
                classNameDescription={styles["price-item-description"]}
                currency={currency}
                showArrow={true}
                productWidthArrow={products[products.length - 1]}
                arrowElement={
                  <svg
                    width="16"
                    height="22"
                    viewBox="0 0 16 22"
                    fill="none"
                    xmlns="http://www.w3.org/2000/svg"
                    className={styles.priceItemArrow}
                  >
                    <path
                      d="M8.70711 0.292892C8.31658 -0.0976315 7.68342 -0.0976315 7.29289 0.292892L0.928932 6.65685C0.538408 7.04738 0.538408 7.68054 0.928932 8.07107C1.31946 8.46159 1.95262 8.46159 2.34315 8.07107L8 2.41421L13.6569 8.07107C14.0474 8.46159 14.6805 8.46159 15.0711 8.07107C15.4616 7.68054 15.4616 7.04738 15.0711 6.65685L8.70711 0.292892ZM8 22H9L9 1H8H7L7 22H8Z"
                      fill="#224E90"
                    />
                  </svg>
                }
                click={handlePriceItem}
                displayMode={["v2", "v4"].includes(trialButtonVariant) ? "grid" : "row"}
                pricesDescription={
                  ["v2", "v4"].includes(trialButtonVariant)
                    ? [
                        translate("/trial-choice.price-descriptions.1"),
                        translate("/trial-choice.price-descriptions.2"),
                        translate("/trial-choice.price-descriptions.3"),
                        translate("/trial-choice.price-descriptions.4"),
                      ]
                    : []
                }
              />
            </div>
            <p className={styles["auxiliary-text"]}>
              {translate(
                `${getProperty("text.1")?.value}.${trialPriceTextVariant}`,
                {
                  price: maxTrialPrice,
                  br: <br />,
                }
              )}
            </p>
          </div>

          <Button
            className={`${styles.button} ${
              ["v1", "v2", "v3", "v4"].includes(trialButtonVariant)
                ? styles["button-v1"]
                : ""
            } ${
              isDisabled && ["v1", "v2", "v3", "v4"].includes(trialButtonVariant)
                ? styles["button-v1-disabled"]
                : ""
            }`}
            disabled={
              isDisabled && !["v1", "v2", "v3", "v4"].includes(trialButtonVariant)
            }
            onClick={handleNext}
          >
            {translate("next")}
          </Button>
          <div ref={bottomRef} />
        </>
      )}
      {(isPending || !isReadyTrialPrice || !isReadyTrialButton) && (
        <Loader className={styles.loader} />
      )}
    </div>
  );
}

export default TrialChoice;
