import Title from "@/components/Title";
import Header from "./components/Header";
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 metricService, { EGoals, EMetrics } from "@/services/metric/metricService";
import { IFunnelPaymentVariant } from "@/api/resources/Session";
import { useFunnel } from "@/hooks/funnel/useFunnel";
import { ELocalesPlacement } from "@/locales";

function TrialPaymentPage() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const birthdate = useSelector(selectors.selectBirthdate);
  const zodiacSign = getZodiacSignByDate(birthdate);
  const {
    gender,
    birthPlace,
    partnerBirthPlace,
    partnerBirthdate,
    partnerGender,
    goal,
    flowChoice,
  } = useSelector(selectors.selectQuestionnaire);
  const partnerZodiacSign = getZodiacSignByDate(partnerBirthdate);
  const [_isOpenPaymentModal, setIsOpenPaymentModal] = useState<boolean>(false);
  const [marginTopTitle, setMarginTopTitle] = useState<number>(360);
  const [singleOrWithPartner, setSingleOrWithPartner] = useState<
    "single" | "partner"
  >("single");
  const { subPlan } = useParams();
  const { products } = useFunnel({
    funnel: ELocalesPlacement.V1,
    paymentPlacement: "main"
  });
  const activeProductFromStore = useSelector(selectors.selectActiveProduct);
  const [activeProduct, setActiveProduct] = useState<IFunnelPaymentVariant | null>(
    activeProductFromStore
  );

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

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

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

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

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

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

  return (
    <section className={`${styles.page} page`}>
      <Header buttonClick={openPaymentModal} />
      {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}
        style={{ marginTop: `${marginTopTitle + 20}px` }}
      >
        Your Personalized Clarity & Love Reading is ready!
      </Title>
      <Goal goal={goal} />
      <PaymentTable product={activeProduct} buttonClick={openPaymentModal} />
      <YourReading
        gender={gender}
        zodiacSign={zodiacSign}
        buttonClick={openPaymentModal}
        singleOrWithPartner={singleOrWithPartner}
      />
      <Title
        variant="h2"
        className={styles.title}
        style={{ marginTop: "88px" }}
      >
        Users love us
      </Title>
      <Reviews reviews={trialPaymentReviews} />
      <PointsList title="What you get" points={trialPaymentPointsList} />
      <OftenAsk />
      <PaymentTable product={activeProduct} buttonClick={openPaymentModal} />
    </section>
  );
}

export default TrialPaymentPage;
