"use client";

import { useEffect, useRef } from "react";

import type { LoginStatus } from "@/data/dto/auth";
import { behaviorAnalytics } from "@/lib/analytics";
import { ROUTES } from "@/router/routes";
import { useAppNavigator } from "@/router/use-app-navigator";
import type { ChatUpgradeReason } from "@/stores/chat/chat-state";
import { useUserSelector } 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 isVip = useUserSelector((state) => state.context.isVip);
  const view = getInsufficientCreditsMessageLimitView(loginStatus);
  const visible = shouldShowMessageLimitBanner({
    upgradePromptVisible,
    upgradeReason,
  });
  const trackedVisibleRef = useRef(false);

  useEffect(() => {
    if (!visible) {
      trackedVisibleRef.current = false;
      return;
    }
    if (trackedVisibleRef.current) return;
    trackedVisibleRef.current = true;
    behaviorAnalytics.paywallShown(
      {
        entryPoint: "chat_input",
        triggerReason: "insufficient_credits",
      },
      { isVip },
    );
  }, [isVip, visible]);

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

    navigator.openSubscription({
      type: getInsufficientCreditsSubscriptionType(isVip),
      returnTo: "chat",
      analytics: {
        entryPoint: "chat_input",
        triggerReason: "insufficient_credits",
      },
    });
  }

  return {
    ...view,
    visible,
    unlock,
  };
}
