"use client";

import { useTranslations } from "next-intl";

import { Button, Spinner, Typography } from "@/components/ui";
import { BlurComponent } from "@/components/widgets";
import { useSingleCheckout } from "@/hooks/payment/useSingleCheckout";
import { useToast } from "@/providers/toast-provider";

import { useProductSelection } from "../ProductSelectionProvider";

import styles from "./AddGuidesButton.module.scss";

import { useMultiPageNavigationContext } from "..";

export default function AddGuidesButton() {
  const t = useTranslations("AdditionalPurchases.add-guides");
  const { addToast } = useToast();
  const { selectedProduct } = useProductSelection();
  const { navigation } = useMultiPageNavigationContext();

  const { handleSingleCheckout, isLoading } = useSingleCheckout({
    onSuccess: () => {
      navigation.goToNext();
    },
    onError: _error => {
      addToast({
        variant: "error",
        message: t("payment_error"),
        duration: 5000,
      });
    },
  });

  const handlePurchase = () => {
    if (!selectedProduct) {
      addToast({
        variant: "error",
        message: t("select_product_error"),
        duration: 5000,
      });
      return;
    }

    handleSingleCheckout({
      productId: selectedProduct.id,
      key: selectedProduct.key,
    });
  };

  const handleSkipOffer = () => {
    navigation.goToNext();
  };

  const isSkipOffer = selectedProduct?.id === "main_skip_offer";

  return (
    <BlurComponent isActiveBlur={true} className={styles.container}>
      <Button
        className={styles.button}
        onClick={isSkipOffer ? handleSkipOffer : handlePurchase}
        disabled={isLoading}
      >
        {isLoading ? (
          <Spinner />
        ) : (
          <Typography weight="semiBold" color="white">
            {isSkipOffer ? t("skip_offer") : t("button")}
          </Typography>
        )}
      </Button>
    </BlurComponent>
  );
}
