"use client";

import { useRouter } from "next/navigation";
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 { ROUTES } from "@/shared/constants/client-routes";

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

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

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

  const { handleSingleCheckout, isLoading } = useSingleCheckout({
    onSuccess: () => {
      router.push(ROUTES.home());
    },
    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 = () => {
    router.push(ROUTES.home());
  };

  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>
  );
}
