import Title from "@/components/Title";
import styles from "./styles.module.css";
import MainButton from "@/components/MainButton";
import PaymentDiscountTable from "./PaymentDiscountTable";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { ELocalesPlacement } from "@/locales";
import { useFunnel } from "@/hooks/funnel/useFunnel";

function TrialPaymentWithDiscount() {
  const dispatch = useDispatch();
  const { products } = useFunnel({
    funnel: ELocalesPlacement.V1,
    paymentPlacement: "main"
  });
  const productFromStore = useSelector(selectors.selectActiveProduct);

  const [_isOpenPaymentModal, setIsOpenPaymentModal] = useState<boolean>(false);

  useEffect(() => {
    if (!products.length) return;
    const activeProduct = products.find(
      (p) => p.trialPrice === productFromStore?.trialPrice
    );
    if (!activeProduct) {
      dispatch(actions.payment.update({ activeProduct: products[0] }));
    }
    if (activeProduct) {
      dispatch(actions.payment.update({ activeProduct }));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dispatch, products]);

  return (
    <section className={`${styles.page} page`}>
      <img
        className={styles["party-popper"]}
        src="/party_popper.webp"
        alt="Party popper"
      />
      <Title variant="h2" className={styles.title}>
        You get a secret discount!
      </Title>
      <PaymentDiscountTable />
      <MainButton
        className={styles.button}
        onClick={() => setIsOpenPaymentModal(true)}
      >
        Start your 3-day trial
      </MainButton>
      <p className={styles.policy}>
        By continuing you agree that if you don`t cancel prior to the end of the
        3-days trial, you will automatically be charged $
        {(productFromStore?.price || 0) / 100} for the introductory period of 14
        days thereafter the standard rate of $
        {(productFromStore?.price || 0) / 100} every 14 days until you cancel in
        settings. Learn more about cancellation and refund policy in
        Subscription terms.
      </p>
    </section>
  );
}

export default TrialPaymentWithDiscount;
