"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";

import { Spinner } from "@/components/ui";
import { performUserSubscriptionAction } from "@/entities/subscriptions/actions";
import { useRetainingStore } from "@/providers/retaining-store-provider";
import { useToast } from "@/providers/toast-provider";
import { ROUTES } from "@/shared/constants/client-routes";

import { RetainingButton } from "../..";

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

export default function Buttons() {
  const t = useTranslations("CancellationOfSubscription");
  const router = useRouter();
  const { addToast } = useToast();

  const { cancellingSubscription, journey } = useRetainingStore(state => state);

  const [isLoadingOfferButton, setIsLoadingOfferButton] =
    useState<boolean>(false);
  const [isLoadingCancelButton, setIsLoadingCancelButton] =
    useState<boolean>(false);

  const handleOfferButtonClick = async () => {
    if (isLoadingOfferButton || isLoadingCancelButton) return;
    setIsLoadingOfferButton(true);
    const response = await performUserSubscriptionAction({
      subscriptionId: cancellingSubscription?.id || "",
      action: "pause_60",
      retainingJourney: journey || undefined,
    });

    if (response?.data?.status === "success") {
      return router.push(ROUTES.retainingFunnelSubscriptionStopped());
    }
    setIsLoadingOfferButton(false);
    addToast({
      variant: "error",
      message: t("error_message"),
      duration: 5000,
    });
  };

  const handleCancelClick = async () => {
    if (isLoadingOfferButton || isLoadingCancelButton) return;
    setIsLoadingCancelButton(true);

    const response = await performUserSubscriptionAction({
      subscriptionId: cancellingSubscription?.id || "",
      action: "cancel",
      retainingJourney: journey || undefined,
    });

    if (response?.data?.status === "success") {
      return router.push(ROUTES.retainingFunnelPlanCancelled());
    }
    setIsLoadingCancelButton(false);
    addToast({
      variant: "error",
      message: t("error_message"),
      duration: 5000,
    });
  };

  return (
    <>
      <RetainingButton
        className={styles.buttonOffer}
        active={true}
        onClick={handleOfferButtonClick}
      >
        {isLoadingOfferButton && (
          <div className={styles.loaderContainer}>
            <Spinner />
          </div>
        )}
        {t("offer_button")}
      </RetainingButton>
      <RetainingButton
        className={styles.buttonCancel}
        onClick={handleCancelClick}
      >
        {isLoadingCancelButton && (
          <div className={styles.loaderContainer}>
            <Spinner />
          </div>
        )}
        {t("cancel_button")}
      </RetainingButton>
    </>
  );
}
