import PaymentPage from "@/components/Payment/nmi/PaymentPage";
import styles from "./styles.module.scss";
import routes from "@/routes";
import { actions, selectors } from "@/store";
import { useEffect, useState } from "react";
import { ESourceAuthorization } from "@/api/resources/User";
import { useSession } from "@/hooks/session/useSession";
import { useLocation, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import Loader, { LoaderColor } from "@/components/Loader";
import { ELocalesPlacement } from "@/locales";
import { useFunnel } from "@/hooks/funnel/useFunnel";

function AnonymousPaymentPage() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { products } = useFunnel({
    funnel: ELocalesPlacement.EmailGenerator,
    paymentPlacement: "TODO:FUNNEL",
  });
  const activeProduct = products[0];
  const activeProductFromStore = useSelector(selectors.selectActiveProduct);
  const { session, createSession } = useSession();
  const utm = useSelector(selectors.selectUTM);
  const feature = useSelector(selectors.selectFeature);
  const [isParametersInitialized, setIsParametersInitialized] = useState(false);

  const location = useLocation();

  useEffect(() => {
    const _feature = location.pathname.replace(
      routes.client.anonymousPayment(),
      ""
    );
    dispatch(
      actions.userConfig.setFeature(
        _feature.includes("/v1/gender") ? "" : _feature
      )
    );
    dispatch(actions.privacyPolicy.updateChecked(true));
  }, [dispatch, location.pathname]);

  useEffect(() => {
    if (!isParametersInitialized) {
      return setIsParametersInitialized(true);
    }
    (async () => {
      await createSession(ESourceAuthorization["aura.test.payment"]);
    })();
  }, [utm, feature, isParametersInitialized]);

  useEffect(() => {
    if (!!activeProduct) {
      dispatch(
        actions.payment.update({
          activeProduct,
        })
      );
    }
  }, [activeProduct]);

  function onPaymentError(error?: string | null): void {
    if (error === "Product not found") {
      return navigate(routes.client.compatibilityV2TrialChoice());
    }
  }

  function onPaymentSuccess(): void {
    setTimeout(() => {
      navigate(routes.client.home());
    }, 1500);
  }

  return (
    <div className={styles.container}>
      {!!activeProductFromStore && session?.["aura.test.payment"]?.length ? (
        <PaymentPage
          // placementKey={EPlacementKeys["aura.placement.payment"]}
          funnel={ELocalesPlacement.EmailGenerator}
          paymentPlacement="TODO:FUNNEL"
          onError={onPaymentError}
          onSuccess={onPaymentSuccess}
          isBackButtonVisible={false}
          isAnonymous={true}
          sessionId={session?.["aura.test.payment"]}
        />
      ) : (
        <Loader color={LoaderColor.Black} />
      )}
    </div>
  );
}

export default AnonymousPaymentPage;
