import Title from "@/components/Title";
import styles from "./styles.module.css";
import PaymentForm from "../PaymentWithEmailPage/PaymentForm";
import { getPriceCentsToDollars } from "@/services/price";
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 {
    product,
    paymentIntent,
    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} />}
      {!isLoadingSinglePayment &&
        paymentIntent &&
        "paymentIntent" in paymentIntent &&
        !!tokenFromStore.length && (
          <>
            <Title variant="h1" className={styles.title}>
              {getPriceCentsToDollars(product?.price || 0)}$
            </Title>
            <PaymentForm
              stripePublicKey={paymentIntent.paymentIntent.data.public_key}
              clientSecret={paymentIntent.paymentIntent.data.client_secret}
              returnUrl={`${returnUrl}?redirect_type=${product?.key}&force=${isForce}`}
            />
          </>
        )}
      {errorSinglePayment?.error && !isLoadingSinglePayment && (
        <Title variant="h3" style={{ color: "red", margin: 0 }}>
          Something went wrong:{" "}
          {errorSinglePayment?.error?.length && errorSinglePayment?.error}
        </Title>
      )}
    </section>
  );
}

export default SinglePaymentPage;
