"use client";

import { useState } from "react";
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 { useMultiPageNavigationContext } from "..";
import { useProductSelection } from "../ProductSelectionProvider";

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

export default function VideoGuidesButton() {
  const t = useTranslations("AdditionalPurchases.video-guides");
  const { addToast } = useToast();
  const { selectedProduct } = useProductSelection();
  const { navigation } = useMultiPageNavigationContext();
  const [isNavigating, setIsNavigating] = useState(false);

  const { handleSingleCheckout, isLoading } = useSingleCheckout({
    onSuccess: async () => {
      setIsNavigating(true);
      await navigation.goToNext();
    },
    onError: _error => {
      addToast({
        variant: "error",
        message: t("payment_error"),
        duration: 5000,
      });
    },
    returnUrl: new URL(
      navigation.getNextPageUrl() || ROUTES.home(),
      process.env.NEXT_PUBLIC_APP_URL || ""
    ).toString(),
  });

  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 isButtonDisabled = isLoading || isNavigating;

  return (
    <BlurComponent isActiveBlur={true} className={styles.container}>
      <Button
        className={styles.button}
        onClick={handlePurchase}
        disabled={isButtonDisabled}
      >
        {isButtonDisabled ? (
          <Spinner />
        ) : (
          <Typography color="white" className={styles.text}>
            {t("button")}
          </Typography>
        )}
      </Button>
      <Button
        className={styles.skipButton}
        variant="ghost"
        onClick={handleSkipOffer}
      >
        <Typography as="p" className={styles.text}>
          {t("skip_button")}
        </Typography>
      </Button>
      <Typography as="p" className={styles.copyright}>
        {t("copyright")}
      </Typography>
    </BlurComponent>
  );
}
