"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 styles from "./AddConsultantButton.module.scss";

export default function AddConsultantButton() {
  const t = useTranslations("AdditionalPurchases.add-consultant");
  const { addToast } = useToast();
  const { navigation } = useMultiPageNavigationContext();
  const data = navigation.currentItem;
  const [isNavigating, setIsNavigating] = useState(false);

  const product = data?.variants?.[0];

  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 handleGetConsultation = () => {
    if (!product) {
      addToast({
        variant: "error",
        message: t("payment_error"),
        duration: 5000,
      });
      return;
    }

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

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

  const isButtonDisabled = isLoading || isNavigating || !product;

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