import Title from "@/components/Title";
import styles from "./styles.module.css";
import MainButton from "@/components/MainButton";
import PaymentDiscountTable from "./PaymentDiscountTable";
import Modal from "@/components/Modal";
import PaymentModal from "@/components/PaymentModal";
import { useEffect, useState } from "react";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys } from "@/api/resources/Paywall";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";

function TrialPaymentWithDiscount() {
  const dispatch = useDispatch();
  const { products } = usePaywall({
    placementKey: EPlacementKeys["aura.placement.secret.discount"],
  });
  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]);

  const handleClose = () => {
    setIsOpenPaymentModal(false);
  };

  return (
    <section className={`${styles.page} page`}>
      <Modal open={isOpenPaymentModal} onClose={handleClose} type="hidden">
        <PaymentModal
          placementKey={EPlacementKeys["aura.placement.secret.discount"]}
        />
      </Modal>
      <img
        className={styles["party-popper"]}
        src="/party_popper.png"
        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;
