import { useApi } from "@/api";
import Loader from "@/components/Loader";
import { useEffect, useState } from "react";
import { Stripe, loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";
import CheckoutForm from "../PaymentPage/methods/Stripe/CheckoutForm";
import { useAuth } from "@/auth";
import styles from "./styles.module.css";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import SubPlanInformation from "../SubPlanInformation";

export function StripePage(): JSX.Element {
  const api = useApi();
  const { token } = useAuth();
  const navigate = useNavigate();
  const activeSubPlan = useSelector(selectors.selectActiveSubPlan);
  const [stripePromise, setStripePromise] =
    useState<Promise<Stripe | null> | null>(null);
  const [clientSecret, setClientSecret] = useState<string>("");
  const [isLoading, setIsLoading] = useState(true);
  if (!activeSubPlan) {
    navigate(routes.client.priceList());
  }

  useEffect(() => {
    (async () => {
      const siteConfig = await api.getAppConfig({ bundleId: "auraweb" });
      setStripePromise(loadStripe(siteConfig.data.stripe_public_key));
    })();
  }, [api]);

  useEffect(() => {
    (async () => {
      const { subscription_receipt } = await api.createSubscriptionReceipt({
        token,
        way: "stripe",
        subscription_receipt: {
          sub_plan_id: activeSubPlan?.id || "stripe.7",
        },
      });
      const { client_secret } = subscription_receipt.data;
      setClientSecret(client_secret);
      setIsLoading(false);
    })();
  }, [api, token]);

  return (
    <div className={`${styles.page} page`}>
      {isLoading ? (
        <div className={styles["payment-loader"]}>
          <Loader />
        </div>
      ) : null}
      {stripePromise && clientSecret && (
        <Elements stripe={stripePromise} options={{ clientSecret }}>
          <CheckoutForm>
            {activeSubPlan && <SubPlanInformation subPlan={activeSubPlan} />}
          </CheckoutForm>
        </Elements>
      )}
    </div>
  );
}
