import Title from "@/components/Title";
import styles from "./styles.module.scss";
import { ISignUpOffer } from "@/data/additionalPurchases";
import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
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 { useApi } from "@/api";
import Loader, { LoaderColor } from "@/components/Loader";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";
import Caution from "../../components/Caution";
import FooterButton from "@/components/pages/AdditionalPurchases/components/FooterButton";
import SignUpOffer from "../../components/SignUpOffer";
import { useFunnel } from "@/hooks/funnel/useFunnel";

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

interface IAddGuidesProps {
  funnel: ELocalesPlacement
  paymentPlacement: string
}

function AddGuides({
  funnel,
  paymentPlacement
}: IAddGuidesProps) {
  const navigate = useNavigate();
  const { translate } = useTranslations(ELocalesPlacement.PalmistryV1);
  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 loadData = useCallback(async () => {
  //   return await api.getSinglePaymentProducts({ token: tokenFromStore });
  // }, [api, tokenFromStore]);

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

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

  const offers = useMemo(() => {
    if (!products) return [];
    const _offers = products?.map((product) => {
      console.log("PRODUCTKEY", product.key);
      const translateKey = `/add-guides.products.${product.key?.replaceAll(".", "_")}`;

      const offer: ISignUpOffer = {
        id: product.id,
        title: translate(`${translateKey}.title`),
        productKey: product.key,
        price: {
          current: product.price,
          old: product.oldPrice,
          discount: ((product.oldPrice || 0) - product.price) / (product.oldPrice || 0) * 100,
        },
        emoji: translate(`${translateKey}.emoji`),
      };
      const subtitle = translate(`${translateKey}.description`);
      if (subtitle !== `${translateKey}.description`) {
        offer.subtitle = subtitle;
      }
      return offer;
    });

    _offers.push({
      id: "main_skip_offer",
      title: translate("/add-guides.products.main_skip_offer.title"),
      subtitle: translate("/add-guides.products.main_skip_offer.description"),
      productKey: "main.skip.offer",
      price: {
        current: 0,
        old: 0,
        discount: 100,
      },
      emoji: translate("/add-guides.products.main_skip_offer.emoji"),
    });

    return _offers;
  }, [products, translate]);

  const [activeOffer, setActiveOffer] = useState<ISignUpOffer | null>(null);

  useEffect(() => {
    if (offers.length) {
      console.log("OFFER");
      setActiveOffer(offers[0]);
    }
  }, [offers]);

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

  const handleNext = () => {
    navigate(`${routes.client.getInformationPartner()}?path=back`);
  };

  const handleClick = async () => {
    try {
      if (!userFromStore || !activeOffer) return;
      if (activeOffer.id === "main_skip_offer") {
        return handleNext();
      }
      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 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 || !activeOffer) return <Loader color={LoaderColor.Black} />;

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

export default AddGuides;
