"use client";

import type { LoginStatus } from "@/data/dto/auth";
import { ROUTES } from "@/router/routes";
import { useAppNavigator } from "@/router/use-app-navigator";
import type { ChatUpgradeReason } from "@/stores/chat/chat-state";
import { useUserState } from "@/stores/user/user-context";

import {
  getInsufficientCreditsMessageLimitView,
  getInsufficientCreditsSubscriptionType,
  shouldShowMessageLimitBanner,
  type InsufficientCreditsMessageLimitView,
} from "../chat-screen.helpers";

export interface UseChatMessageLimitBannerInput {
  upgradePromptVisible: boolean;
  upgradeReason: ChatUpgradeReason | null;
  loginStatus: LoginStatus;
}

export interface ChatMessageLimitBannerView
  extends InsufficientCreditsMessageLimitView {
  visible: boolean;
  unlock: () => void;
}

export function useChatMessageLimitBanner({
  upgradePromptVisible,
  upgradeReason,
  loginStatus,
}: UseChatMessageLimitBannerInput): ChatMessageLimitBannerView {
  const navigator = useAppNavigator();
  const userState = useUserState();
  const view = getInsufficientCreditsMessageLimitView(loginStatus);

  function unlock(): void {
    if (view.action === "auth") {
      navigator.openAuth(ROUTES.chat);
      return;
    }

    navigator.openSubscription({
      type: getInsufficientCreditsSubscriptionType(userState.isVip),
      returnTo: "chat",
    });
  }

  return {
    ...view,
    visible: shouldShowMessageLimitBanner({
      upgradePromptVisible,
      upgradeReason,
    }),
    unlock,
  };
}
