import Title from "@/components/Title";
import styles from "./styles.module.css";
import { useSinglePayment } from "@/hooks/payment/useSinglePayment";
import routes from "@/routes";
import { useAuth } from "@/auth";
import Loader, { LoaderColor } from "@/components/Loader";
import { useCallback, useEffect } from "react";
import { EProductKeys } from "@/data/products";

interface ISinglePaymentPage {
  productId: EProductKeys;
  isForce?: boolean;
}

function SinglePaymentPage({ productId, isForce: _ = false }: ISinglePaymentPage) {
  const {
    isLoading: isLoadingSinglePayment,
    error: errorSinglePayment,
    createSinglePayment,
  } = useSinglePayment();
  const { user: userFromStore, token: tokenFromStore } = useAuth();

  const returnUrl = `${window.location.protocol}//${
    window.location.host
  }${routes.client.paymentResult()}`;

  const createPayment = useCallback(async () => {
    if (!tokenFromStore.length || !userFromStore) {
      return;
    }
    await createSinglePayment({
      user: userFromStore,
      token: tokenFromStore,
      targetProductKey: productId || "",
      returnUrl,
    });
  }, [
    createSinglePayment,
    productId,
    returnUrl,
    tokenFromStore,
    userFromStore,
  ]);

  useEffect(() => {
    createPayment();
  }, [createPayment]);

  return (
    <section className={`${styles.page} page`}>
      {isLoadingSinglePayment && <Loader color={LoaderColor.Black} />}
      {errorSinglePayment?.error && !isLoadingSinglePayment && (
        <Title variant="h3" style={{ color: "red", margin: 0 }}>
          Something went wrong:{" "}
          {errorSinglePayment?.error?.length && errorSinglePayment?.error}
        </Title>
      )}
    </section>
  );
}

export default SinglePaymentPage;
