import Title from "@/components/Title";
import ThankYouBanner from "../../components/ThankYouBanner";
import styles from "./styles.module.css";
import { signUpOffers } from "@/data/additionalPurchases";
import SignUpOffer from "../../components/SignUpOffer";
import { useCallback, useState } from "react";
import { useNavigate } from "react-router-dom";
import FooterButton from "../../components/FooterButton";
import routes from "@/routes";
import PaymentAddress from "../../components/PaymentAddress";
import { createSinglePayment } from "@/services/singlePayment";
import { ResponsePost } from "@/api/resources/SinglePayment";
import { useAuth } from "@/auth";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import { SinglePayment, useApi, useApiCall } from "@/api";
import Loader, { LoaderColor } from "@/components/Loader";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";

function AddReportPage() {
  const navigate = useNavigate();
  const { translate } = useTranslations(ELocalesPlacement.V1);
  const { user: userFromStore } = useAuth();
  const api = useApi();
  const tokenFromStore = useSelector(selectors.selectToken);
  const [_paymentIntent, setPaymentIntent] = useState<ResponsePost | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);
  const [activeOffer, setActiveOffer] = useState(signUpOffers[0]);
  const returnUrl = `${window.location.protocol}//${window.location.host
    }${routes.client.unlimitedReadings()}`;

  const loadData = useCallback(async () => {
    return await api.getSinglePaymentProducts({ token: tokenFromStore });
  }, [api, tokenFromStore]);

  const { data: products, isPending: isPendingProducts } =
    useApiCall<SinglePayment.ResponseGet[]>(loadData);

  const getCurrentProduct = (id: string) => {
    return products?.find((product) => product.key === id) || null;
  };

  const handleClick = async () => {
    try {
      if (!userFromStore || !activeOffer) return;
      const currentProduct = getCurrentProduct(activeOffer?.productKey);
      if (!currentProduct) return;
      setIsLoading(true);
      const { _id, key } = currentProduct;
      const paymentInfo = {
        productId: _id,
        key,
      };
      const paymentIntent = await createSinglePayment(
        userFromStore,
        paymentInfo,
        tokenFromStore,
        userFromStore.email,
        userFromStore.profile.full_name,
        userFromStore.profile.birthday,
        returnUrl,
        api
      );
      setPaymentIntent(paymentIntent);
      if ("payment" in paymentIntent) {
        if (paymentIntent.payment.status === "paid")
          return navigate(routes.client.unlimitedReadings());
        return setIsError(true);
      }
    } catch (error) {
      setIsError(true);
    } finally {
      setIsLoading(false);
    }
  };

  const handleClickSkip = () => {
    navigate(routes.client.unlimitedReadings());
  };

  return (
    <div className={styles.container}>
      <ThankYouBanner />
      <Title variant="h2" className={styles.title}>
        {translate("/add-report.choose_offer")}
      </Title>
      <Title variant="h3" className={styles.subtitle}>
        {translate("/add-report.available_only_now")}
      </Title>
      <div className={styles["offers-container"]}>
        {!isPendingProducts &&
          signUpOffers.map((offer, index) => (
            <SignUpOffer
              key={index}
              isActive={offer.id === activeOffer.id}
              onClick={() => setActiveOffer(offer)}
              {...offer}
              price={{
                ...offer.price,
                current: getCurrentProduct(offer.productKey)?.price || 0,
              }}
            />
          ))}
        {isPendingProducts && <Loader color={LoaderColor.Black} />}
      </div>
      <p className={styles.description}>
        {translate("/add-report.description")}
      </p>
      {isError && (
        <p className={`${styles.description} ${styles.error}`}>
          {translate("went_wrong")}
        </p>
      )}
      <PaymentAddress />
      <FooterButton
        onClick={handleClick}
        onClickSkip={handleClickSkip}
        disabled={isPendingProducts || isLoading}
      >
        {isLoading ? (
          <Loader color={LoaderColor.White} />
        ) : (
          translate("/add-report.get_my_copy")
        )}
      </FooterButton>
    </div>
  );
}

export default AddReportPage;
