import { useSelector } from "react-redux";
import PaymentInformation from "../../components/PaymentInformation";
import styles from "./styles.module.scss";
import { selectors } from "@/store";
import { getFormattedPrice } from "@/utils/price.utils";
import Guarantees from "../../components/Guarantees";
import Button from "../../components/Button";
import { addCurrency, ELocalesPlacement } from "@/locales";
import { useTranslations } from "@/hooks/translations";
import Stars from "../../components/Stars";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys } from "@/api/resources/Paywall";
import { useNavigate } from "react-router-dom";
import { useEffect } from "react";
import routes from "@/routes";

// const placementKey = EPlacementKeys['aura.placement.compatibility.v2'];

function Payment() {
  const navigate = useNavigate();
  const { products, currency, getText } = usePaywall({
    placementKey: EPlacementKeys["aura.placement.compatibility.v2"],
    localesPlacement: ELocalesPlacement.CompatibilityV2,
  });
  const { translate } = useTranslations(ELocalesPlacement.CompatibilityV2);
  const activeProductFromStore = useSelector(selectors.selectActiveProduct);

  const trialPrice = activeProductFromStore?.trialPrice || 0;
  const fullPrice = activeProductFromStore?.price || 0;
  // const isShowPaymentModal = useSelector(
  //   selectors.selectCompatibilityV2IsShowPaymentModalV1
  // );
  // const [isPaymentSuccess, setIsPaymentSuccess] = useState(false);
  // const [isPaymentError, setIsPaymentError] = useState(false);
  // const [isPaymentModalOpen, setIsPaymentModalOpen] = useState(false);

  // const onPaymentError = (error?: string) => {
  //   setIsPaymentError(true);
  //   if (error === "Product not found") {
  //     return navigate(routes.client.compatibilityV2TrialChoice());
  //   }
  //   metricService.reachGoal(EGoals.PAYMENT_ERROR, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
  // }

  // const onPaymentSuccess = () => {
  //   setIsPaymentSuccess(true);
  //   // metricService.reachGoal(EGoals.PAYMENT_SUCCESS);
  //   // if (activeProductFromStore) {
  //   //   metricService.reachGoal(EGoals.PURCHASE, [EMetrics.FACEBOOK], {
  //   //     currency: "USD",
  //   //     value: ((activeProductFromStore.trialPrice || 100) / 100).toFixed(2),
  //   //   });
  //   // }

  //   metricService.reachGoal(EGoals.PAYMENT_SUCCESS, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
  //   metricService.reachGoal(EGoals.PURCHASE, [EMetrics.FACEBOOK], {
  //     currency: "USD",
  //     value: ((activeProductFromStore?.trialPrice || 100) / 100).toFixed(2),
  //   });
  //   setTimeout(() => {
  //     navigate(routes.client.compatibilityV2SkipTrial());
  //   }, 1500);
  // }

  // const onModalClosed = () => {
  //   setIsPaymentModalOpen(false);
  //   navigate(routes.client.compatibilityV2SaveOff());
  // }

  const handlePayment = () => {
    // dispatch(actions.compatibilityV2.setIsShowPaymentModalV1(true));
    // metricService.reachGoal(EGoals.PAYMENT_METHODS_OPENED, [EMetrics.YANDEX, EMetrics.KLAVIYO]);
    // metricService.reachGoal(EGoals.AURA_PAYMENT_METHODS_OPENED, [EMetrics.KLAVIYO]);
    // setIsPaymentModalOpen(true);
    navigate(routes.client.compatibilityV2PaymentModal());
  };

  // useEffect(() => {
  //   window.onpopstate = function (_event) {
  //     if (document.location.toString() === `${window.location.origin}${routes.client.compatibilityV2TrialPayment()}`) {
  //       return navigate(routes.client.compatibilityV2SaveOff());
  //     }
  //   };
  //   return () => {
  //     setTimeout(() => {
  //       window.onpopstate = null;
  //     }, 0);
  //   };

  // }, [])

  useEffect(() => {
    if (!products.length) return;
    const _targetProduct = products.find(product => product._id === activeProductFromStore?._id);
    if (!_targetProduct || !activeProductFromStore) {
      navigate(routes.client.compatibilityV2TrialChoice());
    }
  }, [products, activeProductFromStore]);

  return (
    <>
      {/* <PaymentModal
        // containerClassName={styles["modal-content"]}
        open={isPaymentModalOpen}
        onClose={onModalClosed}
      >
        <PaymentForm onPaymentError={onPaymentError} onPaymentSuccess={onPaymentSuccess} placementKey={placementKey} />
      </PaymentModal> */}
      <div className={styles["app-number-one"]}>
        <p className={styles.text}>
          {translate("/payment.app_number_one", {
            color: <span>{translate("/payment.app_number_one_color")}</span>,
          })}
        </p>
        <Stars />
      </div>
      <PaymentInformation />
      <div className={styles["prices-description"]}>
        {translate("/payment.will_be_charged", {
          // trialPrice: addCurrency(getFormattedPrice(trialPrice), currency),
          // fullPrice: (
          //   <s>{addCurrency(getFormattedPrice(fullPrice), currency)}</s>
          // ),
          splitPrice: addCurrency(getFormattedPrice(
            (
              fullPrice / (
                Number(getText("split.price.value")) || 2
              )
            )
          ), currency),
          save: addCurrency(
            getFormattedPrice(fullPrice - trialPrice),
            currency
          ),
          emailReminder: (
            <b>{translate("/payment.will_be_charged_email_reminder")}</b>
          ),
          trialInfo: (
            <b>
              {translate("/payment.will_be_charged_trial_info", {
                trialDuration: activeProductFromStore?.trialDuration,
                trialPrice: addCurrency(
                  getFormattedPrice(trialPrice),
                  currency
                ),
              })}
            </b>
          ),
        })}
      </div>
      <Guarantees />
      {/* {!isShowPaymentModal && ( */}
      <Button className={styles.button} onClick={handlePayment}>
        {translate("/payment.get_personal_prediction")}
      </Button>
      {/* )} */}
      {/* {isPaymentError && (
        <Toast
          variant="error"
          classNameContainer={styles.toast}
        >
          <p>Something went wrong</p>
        </Toast>

      )}
      {isPaymentSuccess && (
        <Toast
          variant="success"
          classNameContainer={styles.toast}
        >
          <p>Payment successful</p>
        </Toast>

      )} */}
    </>

  );
}

export default Payment;
