import { useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { useDispatch } from "react-redux";
import { actions } from "@/store";
import styles from "./styles.module.css";
import Loader from "@/components/Loader";
import { paymentResultPathsOfProducts } from "@/data/products";

function PaymentResultPage(): JSX.Element {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [searchParams] = useSearchParams();
  const status = searchParams.get("redirect_status");
  const redirect_type = searchParams.get("redirect_type");
  const [isLoading] = useState(true);

  useEffect(() => {
    if (status === "succeeded") {
      dispatch(actions.status.update("subscribed"));
      if (
        !paymentResultPathsOfProducts[redirect_type || ""] ||
        !redirect_type
      ) {
        return navigate(paymentResultPathsOfProducts.default.success);
      }
      return navigate(paymentResultPathsOfProducts[redirect_type].success);
    }
    if (!paymentResultPathsOfProducts[redirect_type || ""] || !redirect_type) {
      return navigate(paymentResultPathsOfProducts.default.fail);
    }
    return navigate(paymentResultPathsOfProducts[redirect_type].fail);
  }, [navigate, status, dispatch, redirect_type]);

  return <div className={styles.page}>{isLoading && <Loader />}</div>;
}

export default PaymentResultPage;
