import styles from "./styles.module.scss";
import { useTranslations } from "@/hooks/translations";
import { addCurrency, ELocalesPlacement } from "@/locales";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import { EPaymentMethod } from "@/data/paymentMethods";
import Loader from "@/components/Loader";
import Title from "@/components/Title";
import PaymentMethodsChoice from "../../PaymentMethodsChoice";
import CheckoutForm from "../CheckoutForm";
import { useEffect, useMemo, useState } from "react";
import metricService, {
  EGoals,
  EMetrics,
} from "@/services/metric/metricService";
import Toast from "@/components/pages/ABDesign/v1/components/Toast";
import Header from "@/components/PalmistryV1/components/Header";
import { useNavigate } from "react-router-dom";
import { EUnleashFlags, useUnleash } from "@/hooks/ab/unleash/useUnleash";
import { IFunnelPaymentVariant } from "@/api/resources/Session";
import { useFunnel } from "@/hooks/funnel/useFunnel";

const environments = import.meta.env;

interface IPaymentPageProps {
  isSinglePayment?: boolean;
  className?: string;
  isBackButtonVisible?: boolean;
  isAnonymous?: boolean;
  sessionId?: string;
  funnel: ELocalesPlacement;
  paymentPlacement: string;
  onError?: (error?: string | null) => void;
  onSuccess?: () => void;
  onBack?: () => void;
  onPopState?: () => void;
}

const getPrice = (product: IFunnelPaymentVariant | null) => {
  if (!product) {
    return 0;
  }
  return (product.trialPrice || 0) / 100;
};

function PaymentPage({
  isSinglePayment = false,
  className = "",
  isBackButtonVisible = true,
  isAnonymous = false,
  sessionId = "",
  funnel,
  paymentPlacement,
  onError,
  // onSuccess,
  onBack,
  onPopState,
}: IPaymentPageProps) {
  const navigate = useNavigate();
  const { translate, getPeriodText } = useTranslations(ELocalesPlacement.V1);
  const currency = useSelector(selectors.selectCurrency);
  const activeProduct = useSelector(selectors.selectActiveProduct);
  const token = useSelector(selectors.selectToken);
  const [isPaymentSuccess, setIsPaymentSuccess] = useState(false);
  const [isPaymentError, setIsPaymentError] = useState(false);

  const {
    isPending,
    trialPeriod,
    trialInterval,
    paymentUrl,
    paywallId,
    placementId,
  } = useFunnel({
    funnel,
    paymentPlacement,
  });

  const { isReady, variant: _paymentModalPageVarinat } = useUnleash({
    flag: EUnleashFlags.paymentModalPage,
  });
  const paymentModalPageVarinat = _paymentModalPageVarinat || "v0";

  const isLoading = useMemo(() => !isReady || isPending, [isReady, isPending]);

  const paymentMethodsButtons = [
    {
      id: EPaymentMethod.CREDIT_CARD,
      icon: "/payment-form/credit-card.svg",
      title: translate("payment_modal.credit_card"),
    },
  ];

  function onPaymentError(error?: string | null): void {
    if (error) {
      setIsPaymentError(true);
      if (error !== "Product not found") {
        metricService.reachGoal(EGoals.PAYMENT_ERROR, [
          EMetrics.YANDEX,
          EMetrics.KLAVIYO,
        ]);
      }
    } else {
      setIsPaymentError(false);
    }
    onError?.(error);
  }

  function onPaymentSuccess(): void {
    setIsPaymentSuccess(true);
    metricService.reachGoal(EGoals.PAYMENT_SUCCESS, [
      EMetrics.YANDEX,
      EMetrics.KLAVIYO,
    ]);
    metricService.reachGoal(EGoals.PURCHASE, [EMetrics.FACEBOOK], {
      currency,
      value: ((activeProduct?.trialPrice || 100) / 100).toFixed(2),
    });
    // onSuccess?.();

    const redirectUrl = `${environments.AURA_NEW_SITE_URL}/auth/callback?jwtToken=${token}&nextUrl=/ap`;
    return window.location.replace(redirectUrl);
  }

  function onModalClosed(): void {
    // onBack?.();
  }

  const handleBack = () => {
    onBack ? onBack() : navigate(-1);
  };

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

  useEffect(() => {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const handlePopState = (_event: PopStateEvent) => {
      onPopState?.();
    };

    window.addEventListener("popstate", handlePopState);

    return () => {
      setTimeout(() => {
        window.removeEventListener("popstate", handlePopState);
      }, 0);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  function getTrackingCookiesForRedirect() {
    const cookieObj = Object.fromEntries(
      document.cookie.split("; ").map((c) => c.split("="))
    );

    const result = Object.entries(cookieObj).filter(([key]) => {
      return (
        [
          "_fbc",
          "_fbp",
          "_ym_uid",
          "_ym_d",
          "_ym_isad",
          "_ym_visorc",
          "yandexuid",
          "ymex",
        ].includes(key) ||
        key.startsWith("_ga") ||
        key.startsWith("_gid")
      );
    });

    const queryString = result
      .map(
        ([key, value]) =>
          `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`
      )
      .join("&");

    return queryString;
  }

  if (!isPending && paymentUrl?.length) {
    metricService.userParams({
      isStripe: true,
    });

    const fbPixels = JSON.parse(localStorage.getItem("fb_pixels") || "[]").join(
      ","
    );

    let redirectUrl = `${paymentUrl}?paywallId=${paywallId}&placementId=${placementId}&productId=${
      activeProduct?.id
    }&jwtToken=${token}&price=${(
      (activeProduct?.trialPrice || 100) / 100
    ).toFixed(2)}&currency=${currency}&${getTrackingCookiesForRedirect()}`;

    if (fbPixels.length) {
      redirectUrl += `&fb_pixels=${fbPixels}`;
    }

    window.location.replace(redirectUrl);
    return <></>;
  }

  return (
    <div className={styles.container}>
      <Header
        className={styles.header}
        classNameTitle={styles["header-title"]}
        isBackButtonVisible={isBackButtonVisible}
        onBack={handleBack}
      />
      <div className={styles.cardTypeAttention}>
        <div className={styles.exclamationMark}>
          <svg
            width="2"
            height="14"
            viewBox="0 0 2 14"
            fill="none"
            xmlns="http://www.w3.org/2000/svg"
          >
            <path
              d="M1.875 1.75C1.875 1.26602 1.48398 0.875 1 0.875C0.516016 0.875 0.125 1.26602 0.125 1.75V8.75C0.125 9.23398 0.516016 9.625 1 9.625C1.48398 9.625 1.875 9.23398 1.875 8.75V1.75ZM1 13.125C1.29008 13.125 1.56828 13.0098 1.7734 12.8046C1.97852 12.5995 2.09375 12.3213 2.09375 12.0312C2.09375 11.7412 1.97852 11.463 1.7734 11.2579C1.56828 11.0527 1.29008 10.9375 1 10.9375C0.709919 10.9375 0.43172 11.0527 0.226602 11.2579C0.021484 11.463 -0.09375 11.7412 -0.09375 12.0312C-0.09375 12.3213 0.021484 12.5995 0.226602 12.8046C0.43172 13.0098 0.709919 13.125 1 13.125Z"
              fill="white"
            />
          </svg>
        </div>
        <div className={styles.textContainer}>
          <p className={styles.title}>
            {translate("payment_modal.card_type_attention.title")}
          </p>
          <p className={styles.description}>
            {translate("payment_modal.card_type_attention.description")}
          </p>
        </div>
      </div>
      {isLoading && (
        <div className={styles["payment-modal"]}>
          <div className={styles["payment-loader"]}>
            <Loader />
          </div>
        </div>
      )}
      <div
        className={`${styles["payment-modal"]} ${
          isLoading ? styles.hide : ""
        } ${className}`}
      >
        {!isSinglePayment && paymentModalPageVarinat !== "v2" && (
          <Title variant="h3" className={styles.title}>
            {translate("payment_modal.title")}
          </Title>
        )}
        {!isSinglePayment && paymentModalPageVarinat === "v2" && (
          <Title variant="h3" className={styles.title}>
            {translate("payment_modal.title1")}
          </Title>
        )}
        {paymentModalPageVarinat !== "v2" && (
          <PaymentMethodsChoice
            paymentMethods={paymentMethodsButtons}
            selectedPaymentMethod={paymentMethodsButtons[0].id}
            // eslint-disable-next-line @typescript-eslint/no-empty-function
            onSelectPaymentMethod={() => {}}
          />
        )}
        {paymentModalPageVarinat === "v0" &&
          !isSinglePayment &&
          activeProduct && (
            <div>
              <p className={styles["sub-plan-description"]}>
                {translate("payment_modal.description", {
                  priceForDays: (
                    <b>
                      {translate("payment_modal.price_for_days", {
                        trialPrice: addCurrency(
                          getPrice(activeProduct),
                          currency
                        ),
                        trialPeriod: getPeriodText(
                          trialPeriod,
                          trialInterval || 0,
                          "nominative",
                          "period_adjective"
                        ),
                      })}
                    </b>
                  ),
                  emailReminder: (
                    <b>{translate("payment_modal.email_reminder")}</b>
                  ),
                })}
              </p>
            </div>
          )}
        {paymentModalPageVarinat === "v1" && (
          <p className={styles["price-information"]}>
            {translate("payment_modal.price_information", {
              price: addCurrency(getPrice(activeProduct), currency),
            })}
          </p>
        )}
        <div
          className={styles["payment-method-container"]}
          style={{
            marginTop:
              paymentModalPageVarinat === "v0" ||
              paymentModalPageVarinat === "v2"
                ? "0px"
                : "18px",
          }}
        >
          {!!activeProduct && (
            <CheckoutForm
              activeProduct={activeProduct}
              isAnonymous={isAnonymous}
              sessionId={sessionId}
              onError={onPaymentError}
              onSuccess={onPaymentSuccess}
              onModalClosed={onModalClosed}
              funnel={funnel}
              paymentPlacement={paymentPlacement}
            />
          )}
        </div>
        <p className={styles.address}>{translate("payment_modal.address")}</p>
      </div>
      {isPaymentError && (
        <Toast variant="error" classNameContainer={styles.toast}>
          <p>{translate("payment_modal.something_went_wrong")}</p>
        </Toast>
      )}
      {isPaymentSuccess && (
        <Toast variant="success" classNameContainer={styles.toast}>
          <p>{translate("payment_modal.payment_successful")}</p>
        </Toast>
      )}
    </div>
  );
}

export default PaymentPage;
