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 { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import { useEffect, useState } from "react";
import { useApi } from "@/api";
import { getClientLocale } from "@/locales";
import { Locale } from "@/components/PaymentTable";
import WithPartnerInformation from "./components/WithPartnerInformation";
import Modal from "@/components/Modal";
import PaymentModal from "./components/PaymentModal";
import { trialPaymentPointsList } from "@/data/pointsLists";
import { trialPaymentReviews } from "@/data/reviews";

const locale = getClientLocale() as Locale;

function TrialPaymentPage() {
  const dispatch = useDispatch();
  const api = useApi();
  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 [subPlans, setSubPlans] = useState<ISubscriptionPlan[]>([]);
  const activeSubPlanFromStore = useSelector(selectors.selectActiveSubPlan);
  const [activeSubPlan, setActiveSubPlan] = useState<ISubscriptionPlan | null>(
    activeSubPlanFromStore
  );
  const [isOpenPaymentModal, setIsOpenPaymentModal] = useState<boolean>(false);
  const [marginTopTitle, setMarginTopTitle] = useState<number>(360);
  const [singleOrWithPartner, setSingleOrWithPartner] = useState<
    "single" | "partner"
  >("single");
  const { subPlan } = useParams();

  useEffect(() => {
    (async () => {
      const { sub_plans } = await api.getSubscriptionPlans({ locale });
      const plans = sub_plans
        .filter((plan: ISubscriptionPlan) => plan.provider === "stripe")
        .sort((a, b) => {
          if (!a.trial || !b.trial) {
            return 0;
          }
          if (a?.trial?.price_cents < b?.trial?.price_cents) {
            return -1;
          }
          if (a?.trial?.price_cents > b?.trial?.price_cents) {
            return 1;
          }
          return 0;
        });
      setSubPlans(plans);
    })();
  }, [api]);

  useEffect(() => {
    if (subPlan) {
      const targetSubPlan = subPlans.find(
        (sub_plan) =>
          String(
            sub_plan?.trial?.price_cents
              ? Math.floor((sub_plan?.trial?.price_cents + 1) / 100)
              : sub_plan.id.replace(".", "")
          ) === subPlan
      );
      if (targetSubPlan) {
        setActiveSubPlan(targetSubPlan);
        dispatch(actions.payment.update({ activeSubPlan: targetSubPlan }));
      }
    }
  }, [dispatch, subPlan, subPlans]);

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

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

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

  const handleDiscount = () => {
    setIsOpenPaymentModal(false);
    navigate(routes.client.additionalDiscount());
  };

  const openStripeModal = () => {
    setIsOpenPaymentModal(true);
  };

  return (
    <section className={`${styles.page} page`}>
      <Modal
        containerClassName={styles.modal}
        open={isOpenPaymentModal}
        onClose={handleDiscount}
      >
        <PaymentModal />
      </Modal>
      <Header buttonClick={openStripeModal} />
      {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 subPlan={activeSubPlan} buttonClick={openStripeModal} />
      <YourReading
        gender={gender}
        zodiacSign={zodiacSign}
        buttonClick={openStripeModal}
        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 subPlan={activeSubPlan} buttonClick={openStripeModal} />
    </section>
  );
}

export default TrialPaymentPage;
