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

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

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

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

  const currentProduct = products?.find(
    (product) => product.key === "main.unique.individual.consultation"
  );

  const handleClick = async () => {
    try {
      if (!userFromStore || !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.getInformationPartner());
        return setIsError(true);
      }
    } catch (error) {
      setIsError(true);
    } finally {
      setIsLoading(false);
    }
  };

  const handleClickSkip = () => {
    navigate(routes.client.getInformationPartner());
  };
  return (
    <div className={styles.container}>
      {!currentProduct?.price && (
        <Loader className={styles.loader} color={LoaderColor.Black} />
      )}
      {!!currentProduct?.price && (
        <>
          <Title variant="h2" className={styles.title}>
            {translate("/add-consultation.more_for_you")}
          </Title>
          <Title variant="h2" className={styles.subtitle}>
            {translate("/add-consultation.exclusive_offer")}
          </Title>
          <ConsultationTable price={currentProduct?.price || 0} />
          <p className={styles.description}>
            {translate("/add-consultation.you_will_be_charged")}
          </p>
          {isError && <p className={styles.error}>{translate("went_wrong")}</p>}
          <FooterButton
            onClick={handleClick}
            onClickSkip={handleClickSkip}
            disabled={isPendingProducts || isLoading}
            classNameButton={styles.button}
          >
            {isPendingProducts || isLoading ? (
              <Loader color={LoaderColor.White} />
            ) : (
              translate("/add-consultation.get_my_consultation")
            )}
          </FooterButton>
          <Copyright />
        </>
      )}
    </div>
  );
}

export default AddConsultationPage;
