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";
import Title from "../Title";
import { useTranslation } from "react-i18next";
import { ISubscriptionPlan } from "@/api/resources/SubscriptionPlans";
import ApplePayButton from "./ApplePayButton";

export function StripePage(): JSX.Element {
  const { i18n } = useTranslation();
  const api = useApi();
  const { token } = useAuth();
  const locale = i18n.language;
  const navigate = useNavigate();
  const activeSubPlan = useSelector(selectors.selectActiveSubPlan);
  const email = useSelector(selectors.selectUser).email;
  const [stripePromise, setStripePromise] =
    useState<Promise<Stripe | null> | null>(null);
  const [subPlans, setSubPlans] = useState<ISubscriptionPlan[] | null>(null);
  const [clientSecret, setClientSecret] = useState<string>("");
  const [subscriptionReceiptId, setSubscriptionReceiptId] =
    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));
      const { sub_plans } = await api.getSubscriptionPlans({ locale });
      setSubPlans(sub_plans);
      const isActiveSubPlan = sub_plans.find(
        (subPlan) => subPlan.id === activeSubPlan?.id
      );
      if (!activeSubPlan || !isActiveSubPlan) {
        navigate(routes.client.priceList());
      }
    })();
  }, [activeSubPlan, api, locale, navigate]);

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

  return (
    <div className={`${styles.page} page`}>
      {isLoading ? (
        <div className={styles["payment-loader"]}>
          <Loader />
        </div>
      ) : null}
      {!isLoading && (
        <>
          <Title variant="h2" className={styles.title}>
            Pay
          </Title>
          <p className={styles.email}>{email}</p>
        </>
      )}
      {stripePromise && clientSecret && subscriptionReceiptId && (
        <Elements stripe={stripePromise} options={{ clientSecret }}>
          <ApplePayButton
            activeSubPlan={activeSubPlan}
            client_secret={clientSecret}
            subscriptionReceiptId={subscriptionReceiptId}
          />
          {activeSubPlan && (
            <SubPlanInformation subPlan={activeSubPlan} subPlans={subPlans} />
          )}
          <CheckoutForm subscriptionReceiptId={subscriptionReceiptId} />
        </Elements>
      )}
    </div>
  );
}
