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

const returnUrl = `${window.location.protocol}//${window.location.host
  }${routes.client.addGuides()}`;

interface IAddConsultantProps {
  funnel: ELocalesPlacement
  paymentPlacement: string
  nextRoute?: string;
}

function AddConsultant({
  funnel,
  paymentPlacement,
  nextRoute = routes.client.addGuides()
}: IAddConsultantProps) {
  const { translate } = useTranslations(ELocalesPlacement.PalmistryV1);
  const navigate = useNavigate();
  const api = useApi();
  const { user: userFromStore } = useAuth();
  const tokenFromStore = useSelector(selectors.selectToken);

  const [isLoading, setIsLoading] = useState(false);
  const [_paymentIntent, setPaymentIntent] = useState<ResponsePost | null>(null);
  const [isError, setIsError] = useState(false);

  const { products, isPending } = useFunnel({
    funnel,
    paymentPlacement
  })

  const currentProduct = products[0]

  // 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 === funnelProducts[0].key
  // );

  const handleNext = () => {
    navigate(nextRoute);
  }

  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 handleNext();
        return setIsError(true);
      }
      if ("status" in paymentIntent && paymentIntent.status === "paid")
        return handleNext();
    } catch (error) {
      setIsError(true);
    } finally {
      setIsLoading(false);
    }
  };

  const handleClickSkip = () => {
    handleNext();
  };

  if (isPending) return <Loader color={LoaderColor.Black} />

  return (
    <div className={styles.page}>
      <Caution />
      <Title variant="h2" className={styles.title}>
        {translate("/add-consultant.more_for_you")}
      </Title>
      <div className={styles["exclusive-offer"]}>
        {translate("/add-consultant.exclusive_offer")}
      </div>
      <ConsultationTable price={currentProduct?.price || 0} />
      {isError && <p className={styles.error}>{translate("went_wrong")}</p>}
      <FooterButton
        onClick={handleClick}
        onClickSkip={handleClickSkip}
        disabled={isLoading}
        classNameButton={styles.button}
        classNameContainer={styles["button-container"]}
      >
        {isLoading ? (
          <Loader color={LoaderColor.White} />
        ) : (
          translate("/add-consultant.get_my_consultation")
        )}
      </FooterButton>
    </div>
  );
}

export default AddConsultant;
