import React, { useRef } from "react";
import { useDispatch } from "react-redux";
import { useSelector } from "react-redux";

import { selectors } from "@/store";
import useSteps, { Step } from "@/hooks/palmistry/use-steps";
import Button from "@/components/palmistry/button/button";
import EmailHeader from "@/components/palmistry/email-header/email-header";
import { actions } from "@/store";
import {
  addCurrency,
  ELocalesPlacement,
  getDefaultLocaleByLanguage,
  language,
} from "@/locales";
import { getPriceCentsToDollars } from "@/services/price";
import { IOutletContext } from "@/routerComponents/Palmistry/v1/LayoutPersonalVideo";
import styles from "./styles.module.scss";
import { useMetricABFlags } from "@/services/metric/metricService";
import { useTranslations } from "@/hooks/translations";
import { useFunnel } from "@/hooks/funnel/useFunnel";

// const bestPlanId = "stripe.15";
const bestPlanId = "";

export default function StepSubscriptionPlan({
  containerVideoRef: videoRef,
  isVisibleElements,
}: Partial<IOutletContext>) {
  const { translate } = useTranslations(ELocalesPlacement.PalmistryV0);
  const steps = useSteps();
  const dispatch = useDispatch();
  const activeProductFromStore = useSelector(selectors.selectActiveProduct);
  const { products } = useFunnel({
    funnel: ELocalesPlacement.PalmistryV0,
    paymentPlacement: "main",
  });
  // const defaultProduct = properties.find(
  //   (property) => property.key === "default.product"
  // )?.value;
  const defaultProduct = products[0].key
  const currency = useSelector(selectors.selectCurrency);
  const storedEmail = steps.getStoredValue(Step.Email);

  const [product, setProduct] = React.useState("");

  const [email, setEmail] = React.useState(steps.getStoredValue(Step.Email));

  const containerVideoRef = useRef<HTMLDivElement>(null);

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

  React.useEffect(() => {
    if (!defaultProduct || activeProductFromStore) return;
    const targetDefaultProduct = products.find((p) => p.key === defaultProduct);
    if (!targetDefaultProduct) return;
    setProduct(targetDefaultProduct.id);
    steps.saveCurrent(targetDefaultProduct.id);
    dispatch(
      actions.payment.update({
        activeProduct: targetDefaultProduct,
      })
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [defaultProduct]);

  React.useEffect(() => {
    if (activeProductFromStore) {
      setProduct(activeProductFromStore.id);
    }
  }, [activeProductFromStore]);

  React.useEffect(() => {
    setEmail(storedEmail || "");
  }, [storedEmail]);

  const onNext = () => {
    if (!product) return;
    const targetProduct = products.find((_product) => _product.id === product);

    if (targetProduct) {
      dispatch(actions.payment.update({ activeProduct: targetProduct }));
    }
    steps.saveCurrent(product);
    steps.goNext();
  };

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

  React.useEffect(() => {
    if (auraVideoTrial === "on") {
      dispatch(actions.personalVideo.updateIsVideoPlaying(true));
    } else {
      dispatch(actions.personalVideo.updateIsVideoPlaying(false));
    }
  }, [auraVideoTrial, dispatch]);

  const isShowDefault = () => {
    if (auraVideoTrial === "on") {
      return false;
    }
    return getDefaultLocaleByLanguage(language) !== "en" || !isLongText;
  };

  return (
    <>
      <EmailHeader email={email} />
      <div ref={containerVideoRef} />
      {auraVideoTrial !== "on" &&
        getDefaultLocaleByLanguage(language) === "en" &&
        isLongText && (
          <p className={styles.text}>
            AURA is the only accurate app with reliable fate line analysis,
            verified by professionals and guaranteed to provide precise
            predictions.
            <br />
            <br />
            AURA has already helped millions of people find happiness and
            discover the whole truth about their relationships.
            <br />
            <br />
            Your fate analysis, which will completely change your life, is
            almost ready! Before we provide it to you, we would like to offer
            you the opportunity to choose the amount you consider reasonable to
            try AURA for 7 days and which you think is fair for the changes that
            will happen to you:
            <br />
            <br />
            You will discover all the most intimate secrets that the stars have
            prepared for you and solve relationship issues within just one
            month;
            <br />
            <br />
            You will once and for all put the finishing touches on unresolved
            issues and forget about problems that have been haunting you for
            years (if not decades);
            <br />
            <br />
            You will save hundreds of dollars on fake and unprofessional
            astrological predictions and fortune tellers;
            <br />
            <br />
            You will receive not only a personal analysis but also personalized
            daily horoscopes, learn who and how is draining your energy, and get
            other personalized readings.
            <br />
            <br />A 7-day trial period costs us $13.76, but please choose the
            amount that suits you best:
          </p>
        )}
      {(isVisibleElements || auraVideoTrial !== "on") && (
        <>
          {isShowDefault() && (
            <>
              <div className={`${styles.title} palmistry-container__title`}>
                {/* {getText("text.0")} */}
              </div>

              <div className={`${styles.image} palmistry-container__image`}>
                <svg
                  width="153"
                  height="133"
                  viewBox="0 0 153 133"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <g clipPath="url(#clip0_16903_24136)">
                    <rect width="153" height="133" fill=""></rect>
                    <path
                      d="M20.5004 33.3398H19.899C19.5382 33.3398 19.2375 33.5995 19.2375 33.9458C18.9368 38.0145 14.4866 42.1697 10.2469 42.5449C9.91613 42.5737 9.64551 42.8623 9.64551 43.1797V43.7857C9.64551 44.1319 9.91612 44.3916 10.2769 44.4205C14.4866 44.709 18.7864 48.8931 19.2375 52.9618C19.2675 53.3369 19.5983 53.6255 20.0193 53.6255H20.4402C20.8612 53.6255 21.192 53.3369 21.222 52.933C21.5829 48.3737 25.4016 44.6225 30.1525 44.3916C30.5434 44.3628 30.814 44.0742 30.814 43.6991V43.1797C30.814 42.8046 30.5133 42.516 30.1525 42.4871C25.3715 42.2563 21.5227 38.4762 21.222 33.8592C21.1619 33.5995 20.8612 33.3398 20.5004 33.3398Z"
                      fill="rgba(172, 209, 255, 0.7)"
                    ></path>
                    <path
                      d="M90.0847 6.81456C86.8721 6.81456 84.2788 4.22585 84.2788 1.01896C84.2788 0.65834 83.995 0.375 83.6337 0.375C83.2725 0.375 82.9886 0.65834 82.9886 1.01896C82.9886 4.22585 80.3953 6.81456 77.1827 6.81456C76.8214 6.81456 76.5376 7.0979 76.5376 7.45851C76.5376 7.81913 76.8214 8.10247 77.1827 8.10247C80.3953 8.10247 82.9886 10.6912 82.9886 13.8981C82.9886 14.2587 83.2725 14.542 83.6337 14.542C83.995 14.542 84.2788 14.2587 84.2788 13.8981C84.2788 10.6912 86.8721 8.10247 90.0847 8.10247C90.446 8.10247 90.7298 7.81913 90.7298 7.45851C90.7298 7.0979 90.446 6.81456 90.0847 6.81456Z"
                      fill="rgba(172, 209, 255, 0.3)"
                    ></path>
                    <path
                      d="M145.334 117.4C139.059 117.4 133.994 112.343 133.994 106.08C133.994 105.376 133.44 104.822 132.734 104.822C132.029 104.822 131.474 105.376 131.474 106.08C131.474 112.343 126.409 117.4 120.135 117.4C119.429 117.4 118.875 117.953 118.875 118.657C118.875 119.362 119.429 119.915 120.135 119.915C126.409 119.915 131.474 124.971 131.474 131.235C131.474 131.939 132.029 132.492 132.734 132.492C133.44 132.492 133.994 131.939 133.994 131.235C133.994 124.971 139.059 119.915 145.334 119.915C146.04 119.915 146.594 119.362 146.594 118.657C146.594 117.953 146.04 117.4 145.334 117.4Z"
                      fill="rgba(172, 209, 255, 0.45)"
                    ></path>
                    <path
                      d="M-5.56678 124.119L138.066 29.6205C142.669 26.5921 148.878 28.0499 151.652 32.8107C154.427 37.5714 152.628 43.6796 147.716 46.1774L-5.56678 124.119Z"
                      fill="url(#paint0_linear_16903_24136)"
                    ></path>
                  </g>
                  <defs>
                    <linearGradient
                      id="paint0_linear_16903_24136"
                      x1="141.466"
                      y1="50.4613"
                      x2="13.2256"
                      y2="125.204"
                      gradientUnits="userSpaceOnUse"
                    >
                      <stop stopColor="#9babd9"></stop>
                      <stop offset="1" stopColor="#EBEFFF"></stop>
                    </linearGradient>
                    <clipPath id="clip0_16903_24136">
                      <rect width="153" height="133" fill="white"></rect>
                    </clipPath>
                  </defs>
                </svg>
              </div>
            </>
          )}

          <div className={`${styles.plans} palmistry-container__plans`}>
            {products.map((_product) => (
              <div
                key={_product.id}
                className={`palmistry-container__plan ${product === _product.id
                    ? "palmistry-container__plan_active"
                    : ""
                  }`}
                onClick={() => setProduct(_product.id)}
              >
                <h3>
                  {addCurrency(
                    getPriceCentsToDollars(_product.trialPrice || 0),
                    currency
                  )}
                </h3>
              </div>
            ))}
          </div>

          <span
            className={`${styles["subscription-text"]
              } palmistry-container__subscription-text ${product === bestPlanId
                ? "palmistry-container__subscription-text_active"
                : ""
              }`}
          >
            {/* {getText("text.1")} */}
          </span>

          <Button
            className={`${styles.button} palmistry-container__button`}
            type="button"
            onClick={onNext}
            active
            disabled={!product}
          >
            {translate("continue")}
          </Button>
        </>
      )}
    </>
  );
}
