import styles from "./styles.module.css";
import Modal from "@/components/Modal";
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 "./CheckoutForm";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import Title from "@/components/Title";
import ApplePayButton from "@/components/StripePage/ApplePayButton";
import SubPlanInformation from "@/components/SubPlanInformation";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import { usePaywall } from "@/hooks/paywall/usePaywall";
import { EPlacementKeys } from "@/api/resources/Paywall";
import { useMakePayment } from "@/hooks/payment/useMakePayment";

interface StripeModalProps {
  open: boolean;
  onClose: () => void;
  // onSuccess: (receipt: SubscriptionReceipts.SubscriptionReceipt) => void;
  // onError: (error: Error) => void;
}

export function StripeModal({
  open,
  onClose,
}: //   onSuccess,
//   onError,
StripeModalProps): JSX.Element {
  const navigate = useNavigate();
  const email = useSelector(selectors.selectUser).email;
  const [stripePromise, setStripePromise] =
    useState<Promise<Stripe | null> | null>(null);

  const { products } = usePaywall({
    placementKey: EPlacementKeys["aura.placement.main"],
  });

  const activeProduct = useSelector(selectors.selectActiveProduct);
  if (!activeProduct) {
    navigate(routes.client.trialChoice());
  }

  const {
    paymentIntentId,
    clientSecret,
    returnUrl: checkoutUrl,
    paymentType,
    publicKey,
    isLoading,
    error,
  } = useMakePayment({
    productId: activeProduct?._id || "",
  });

  if (checkoutUrl?.length) {
    window.location.href = checkoutUrl;
  }

  useEffect(() => {
    (async () => {
      if (!products?.length || !publicKey) return;
      setStripePromise(loadStripe(publicKey));
      const isActiveSubPlan = products.find(
        (product) => product._id === activeProduct?._id
      );
      if (!activeProduct || !isActiveSubPlan) {
        navigate(routes.client.priceList());
      }
    })();
  }, [activeProduct, navigate, products, publicKey]);

  const handleClose = () => {
    onClose();
  };

  if (error?.length) {
    return (
      <div className={styles["payment-modal"]}>
        <Title variant="h3" className={styles.title}>
          Something went wrong
        </Title>
      </div>
    );
  }

  return (
    <Modal open={open} onClose={handleClose}>
      {isLoading ? (
        <div className={styles["payment-loader"]}>
          <Loader />
        </div>
      ) : null}
      {!isLoading && (
        <>
          <Title variant="h2" className={styles.title}>
            Choose payment method
          </Title>
          <p className={styles.email}>{email}</p>
        </>
      )}
      {stripePromise && clientSecret && paymentIntentId && (
        <Elements stripe={stripePromise} options={{ clientSecret }}>
          <ApplePayButton
            activeProduct={activeProduct}
            client_secret={clientSecret}
            subscriptionReceiptId={paymentIntentId}
          />
          {activeProduct && <SubPlanInformation product={activeProduct} />}
          <CheckoutForm
            confirmType={paymentType}
            subscriptionReceiptId={paymentIntentId}
          />
        </Elements>
      )}
    </Modal>
  );
}
