"use client";

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

import { Spinner, Typography } from "@/components/ui";
import { performUserSubscriptionAction } from "@/entities/subscriptions/actions";
import { useLottie } from "@/hooks/lottie/useLottie";
import { useRetainingStore } from "@/providers/retaining-store-provider";
import { useToast } from "@/providers/toast-provider";
import { ROUTES } from "@/shared/constants/client-routes";
import { ELottieKeys } from "@/shared/constants/lottie";
import { ERetainingFunnel } from "@/stores/retaining-store";

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

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

export default function Buttons() {
  const t = useTranslations("CancelSubscription");
  const router = useRouter();
  useLottie({
    preloadKey: ELottieKeys.loaderCheckMark,
  });
  const { addToast } = useToast();

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

  const [activeButton, setActiveButton] = useState<"stay" | "cancel" | null>();
  const [isLoadingButton, setIsLoadingButton] = useState<
    "stay" | "cancel" | null
  >();

  const handleCancelButtonClick = () => {
    if (isLoadingButton) return;
    setActiveButton("cancel");
    const timer = setTimeout(() => {
      router.push(ROUTES.retainingFunnelAppreciateChoice());
    }, 1000);
    return () => clearTimeout(timer);
  };

  const handleStayButtonClick = async () => {
    if (isLoadingButton) return;
    setActiveButton("stay");
    setIsLoadingButton("stay");

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

    if (response?.data?.status === "success") {
      setFunnel(ERetainingFunnel.Stay50);
      return router.push(ROUTES.retainingFunnelStay50Done());
    }
    setIsLoadingButton(null);
    setActiveButton(null);
    addToast({
      variant: "error",
      message: t("error_message"),
      duration: 5000,
    });
  };

  return (
    <div className={styles.buttons}>
      <RetainingButton
        className={styles.button}
        active={activeButton === "stay"}
        onClick={handleStayButtonClick}
      >
        {isLoadingButton === "stay" && (
          <div className={styles.loaderContainer}>
            <Spinner />
          </div>
        )}
        <Typography className={styles.buttonIcon}>🙋‍♀️</Typography>
        {t("stay_button")}
      </RetainingButton>
      <RetainingButton
        className={styles.button}
        active={activeButton === "cancel"}
        onClick={handleCancelButtonClick}
      >
        <Typography className={styles.buttonIcon}>🙅‍♀️</Typography>
        {t("cancel_button")}
      </RetainingButton>
    </div>
  );
}
