import styles from "./styles.module.css";
import PaymentDiscountTable from "./PaymentDiscountTable";
import { useEffect } from "react";
import { selectors } from "@/store";
import { useSelector } from "react-redux";
import { useTranslations } from "@/hooks/translations";
import { addCurrency, ELocalesPlacement } from "@/locales";
import DiscountLayout from "../../layouts/Discount/DiscountLayout";
import QuestionnaireGreenButton from "../../ui/GreenButton";
import { Navigate, useNavigate } from "react-router-dom";
import routes from "@/routes";
import { usePayment } from "@/hooks/payment/nmi/usePayment";
import { useFunnel } from "@/hooks/funnel/useFunnel";

function TrialPaymentWithDiscount() {
  const navigate = useNavigate()
  const { translate } = useTranslations(ELocalesPlacement.V1);
  const activeProduct = useSelector(selectors.selectActiveProduct);
  const currency = useSelector(selectors.selectCurrency);

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

  const { trialInterval } = useFunnel({
    funnel: ELocalesPlacement.V1,
    paymentPlacement: "main"
  });

  const {
    error,
    isPaymentSuccess,
    showCreditCardForm,
  } = usePayment({
    funnel: ELocalesPlacement.V1,
    paymentPlacement: "main",
    activeProduct,
    paymentFormType: "lightbox"
  });

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

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

  const openPaymentModal = () => {
    showCreditCardForm();
  };

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

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

  return (
    <DiscountLayout title={translate("/trial-payment-with-discount.title")}>
      <PaymentDiscountTable />

      <div className={styles['button-wrapper']}>
        <QuestionnaireGreenButton
          className={styles.button}
          onClick={openPaymentModal}
        >
          {translate("/trial-payment-with-discount.button", {
            trialDuration: trialInterval,
          })}
        </QuestionnaireGreenButton>
      </div>
      <p className={`${styles.policy} ${styles.wave}`}>
        {translate("/trial-payment-with-discount.description", {
          trialDuration: trialInterval,
          price: addCurrency((activeProduct?.price || 0) / 100, currency),
        })}
      </p>
    </DiscountLayout>
  );
}

export default TrialPaymentWithDiscount;
