import Title from "@/components/Title";
import PersonalInformation from "./components/PersonalInformation";
import styles from "./styles.module.css";
import Goal from "./components/Goal";
import PaymentTable from "./components/PaymentTable";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { Navigate, useNavigate, useParams } from "react-router-dom";
import routes from "@/routes";
import { getZodiacSignByDate } from "@/services/zodiac-sign";
import YourReading from "./components/YourReading";
import Reviews from "./components/Reviews";
import PointsList from "./components/PointsList";
import OftenAsk from "./components/OftenAsk";
import { useEffect, useState } from "react";
import WithPartnerInformation from "./components/WithPartnerInformation";
import { trialPaymentPointsList } from "@/data/pointsLists";
import { trialPaymentReviews } from "@/data/reviews";
import TrialPaymentHeader from "./components/Header";
import Header from "../../components/Header";
import BackgroundTopBlob from "../../ui/BackgroundTopBlob";
import { useDynamicSize } from "@/hooks/useDynamicSize";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";
import { usePayment } from "@/hooks/payment/nmi/usePayment";
import metricService, { EGoals, EMetrics } from "@/services/metric/metricService";
import { useFunnel } from "@/hooks/funnel/useFunnel";

function TrialPaymentPage() {
  const { translate } = useTranslations(ELocalesPlacement.V1);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const birthdate = useSelector(selectors.selectBirthdate);
  const zodiacSign = getZodiacSignByDate(birthdate);
  const { width: pageWidth, elementRef: pageRef } = useDynamicSize({});
  const {
    gender,
    birthPlace,
    partnerBirthPlace,
    partnerBirthdate,
    partnerGender,
    goal,
    flowChoice,
  } = useSelector(selectors.selectQuestionnaire);
  const partnerZodiacSign = getZodiacSignByDate(partnerBirthdate);
  const { products, currency, trialInterval } = useFunnel({
    funnel: ELocalesPlacement.V1,
    paymentPlacement: "main"
  });
  const activeProduct = useSelector(selectors.selectActiveProduct);
  const [singleOrWithPartner, setSingleOrWithPartner] = useState<
    "single" | "partner"
  >("single");
  const { subPlan } = useParams();


  const {
    error,
    isPaymentSuccess,
    showCreditCardForm,
    isModalClosed
  } = usePayment({
    funnel: ELocalesPlacement.V1,
    paymentPlacement: "main",
    activeProduct: activeProduct || products[0],
    paymentFormType: "lightbox"
  });

  useEffect(() => {
    if (error) {
      onPaymentError();
    }
  }, [error])

  useEffect(() => {
    if (isPaymentSuccess) {
      onPaymentSuccess();
    }
  }, [isPaymentSuccess])

  useEffect(() => {
    if (isModalClosed) {
      onModalClosed()
    }
  }, [isModalClosed])

  const onPaymentSuccess = () => {
    return navigate(routes.client.paymentSuccess())
  }

  const onModalClosed = () => {
    return handleDiscount()
  }

  const onPaymentError = () => {
    return navigate(routes.client.paymentFail())
  }

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

  useEffect(() => {
    if (subPlan) {
      const targetProduct = products.find(
        (product) =>
          String(
            product?.trialPrice
              ? Math.floor((product?.trialPrice + 1) / 100)
              : product.key.replace(".", "")
          ) === subPlan
      );
      if (targetProduct) {
        dispatch(actions.payment.update({ activeProduct: targetProduct }));
      }
    }
  }, [dispatch, subPlan, products]);

  useEffect(() => {
    if (!products.length) return;
    const isActiveProduct = products.find(
      (product) => product.id === activeProduct?.id
    );
    if (!activeProduct || !isActiveProduct) {
      navigate(routes.client.trialChoiceV1());
    }
  }, [activeProduct, navigate, products]);

  useEffect(() => {
    if (["relationship", "married"].includes(flowChoice)) {
      setSingleOrWithPartner("partner");
      return;
    }
    setSingleOrWithPartner("single");
  }, [flowChoice]);

  if (!activeProduct) {
    return <Navigate to={routes.client.trialChoiceV1()} />;
  }

  if (!birthdate || !gender || !birthPlace) {
    return <Navigate to={routes.client.genderV1()} />;
  }

  const handleDiscount = () => {
    navigate(routes.client.additionalDiscountV1());
  };

  const openPaymentModal = () => {
    metricService.reachGoal(EGoals.AURA_PAYMENT_METHODS_OPENED, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
    showCreditCardForm();
  };

  return (
    <section
      className={`${styles.page} page`}
      ref={pageRef}
      style={{
        backgroundColor: gender === "male" ? "#C1E5FF" : "#F7EBFF",
      }}
    >
      <div className={styles["background-top-blob-container"]}>
        <BackgroundTopBlob
          width={pageWidth}
          height={200}
          className={styles["background-top-blob"]}
        />
      </div>
      <Header className={styles.header} />
      <TrialPaymentHeader
        buttonClick={openPaymentModal}
        buttonText={translate("/trial-payment.button") as string}
      />
      {singleOrWithPartner === "partner" && (
        <WithPartnerInformation
          zodiacSign={zodiacSign}
          gender={gender}
          birthPlace={birthPlace}
          birthdate={birthdate}
          partnerBirthPlace={partnerBirthPlace}
          partnerBirthDate={partnerBirthdate}
          partnerGender={partnerGender}
          partnerZodiacSign={partnerZodiacSign}
        />
      )}
      {singleOrWithPartner === "single" && (
        <PersonalInformation
          zodiacSign={zodiacSign}
          gender={gender}
          birthPlace={birthPlace}
          birthdate={birthdate}
        />
      )}
      <Title variant="h2" className={styles.title}>
        {translate("/trial-payment.title1")}
      </Title>
      <Goal goal={goal} />
      <PaymentTable
        gender={gender}
        product={activeProduct}
        trialInterval={trialInterval}
        currency={currency}
        buttonClick={openPaymentModal}
      />
      <YourReading
        gender={gender}
        zodiacSign={zodiacSign}
        buttonClick={openPaymentModal}
        singleOrWithPartner={singleOrWithPartner}
        callToActionText={translate("/trial-payment.to_read_full") as string}
        buttonText={translate("/trial-payment.button") as string}
      />
      <Title variant="h2" className={styles.title}>
        {translate("/trial-payment.users_love_us")}
      </Title>
      <Reviews reviews={trialPaymentReviews} />
      <PointsList
        title={translate("/trial-payment.what_you_get")}
        points={trialPaymentPointsList}
      />
      <OftenAsk />
      <PaymentTable
        gender={gender}
        product={activeProduct}
        trialInterval={trialInterval}
        currency={currency}
        buttonClick={openPaymentModal}
      />
    </section>
  );
}

export default TrialPaymentPage;
