"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";

import { useAuthState } from "@/stores/auth/auth-context";
import { useChatDispatch, useChatState } from "@/stores/chat/chat-context";
import { useUserState } from "@/stores/user/user-context";
import {
  openChatInExternalBrowser,
  recordExternalBrowserPromptShown,
  resolveExternalBrowserPromptEligibility,
} from "@/lib/chat/chat_external_browser";

import { MobileShell } from "@/app/_components/core";

import {
  BrowserHintOverlay,
  ChatArea,
  ChatHeader,
  ChatInputBar,
  ChatQuotaExhaustedBanner,
  ExternalBrowserDialog,
  HistoryUnlockDialog,
  PwaInstallOverlay,
} from "./components";
import {
  deriveIsGuest,
  getChatPaywallNavigationUrl,
  getInsufficientCreditsSubscriptionType,
  isChatDevelopmentEnvironment,
  shouldStartExternalBrowserPrompt,
} from "./chat-screen.helpers";
import styles from "./components/chat-screen.module.css";

export function ChatScreen() {
  const state = useChatState();
  const chatDispatch = useChatDispatch();
  const authState = useAuthState();
  const userState = useUserState();
  const router = useRouter();
  const [showExternalBrowserDialog, setShowExternalBrowserDialog] =
    useState(false);

  // isGuest 派生（chat-screen 是唯一知道这个值的地方 —— chat 机器无 isGuest 字段）
  const isGuest = deriveIsGuest(authState.loginStatus);

  // 消息数量限制由后端统一返回 lockDetail，前端不再处理本地额度。
  const showMessageLimitBanner =
    state.upgradePromptVisible &&
    (state.upgradeReason === "weekly_limit" ||
      state.upgradeReason === "insufficient_credits");
  const messageLimitTitle =
    state.upgradeReason === "insufficient_credits"
      ? "Insufficient credits\nTop up to continue chatting"
      : "The limit for free chat times\nhas been reached";
  const messageLimitCtaLabel =
    state.upgradeReason === "insufficient_credits"
      ? "Top up credits to continue"
      : "Unlock your membership to continue";

  const externalBrowserPromptShownRef = useRef(false);

  useEffect(() => {
    if (
      !shouldStartExternalBrowserPrompt({
        hasInitialized: authState.hasInitialized,
        isLoading: authState.isLoading,
        loginStatus: authState.loginStatus,
      })
    ) {
      return;
    }

    let mounted = true;
    let timer: number | undefined;

    const init = async () => {
      if (externalBrowserPromptShownRef.current) return;

      const eligibility = await resolveExternalBrowserPromptEligibility();
      if (!mounted || !eligibility.canShow) return;

      externalBrowserPromptShownRef.current = true;
      timer = window.setTimeout(() => {
        if (!mounted) return;
        setShowExternalBrowserDialog(true);
        void recordExternalBrowserPromptShown(eligibility.today);
      }, 3000);
    };

    void init();

    return () => {
      mounted = false;
      if (timer !== undefined) window.clearTimeout(timer);
    };
  }, [
    authState.hasInitialized,
    authState.isLoading,
    authState.loginStatus,
  ]);

  async function handleOpenExternalBrowser(): Promise<void> {
    setShowExternalBrowserDialog(false);
    await openChatInExternalBrowser();
  }

  function openChatPaywallSubscription(): void {
    router.push(getChatPaywallNavigationUrl(authState.loginStatus));
  }

  function handleUnlockPrivateMessage(): void {
    openChatPaywallSubscription();
  }

  function handleMessageLimitUnlock(): void {
    const subscriptionType =
      state.upgradeReason === "insufficient_credits"
        ? getInsufficientCreditsSubscriptionType(userState.isVip)
        : "vip";

    router.push(
      getChatPaywallNavigationUrl(
        authState.loginStatus,
        subscriptionType,
      ),
    );
  }

  function handleUnlockVoiceMessage(): void {
    openChatPaywallSubscription();
  }

  return (
    <MobileShell>
      <div className={styles.shell}>
        <div className={styles.background}>
          <Image
            src="/images/chat/bg-chatpage.png"
            alt=""
            fill
            priority
            sizes="(max-width: 500px) 100vw, 500px"
          />
        </div>

        <div className={styles.layout}>
          {/* isGuest 派生自 auth.loginStatus */}
          <ChatHeader isGuest={isGuest} />

          <ChatArea
            messages={state.messages}
            isReplyingAI={state.isReplyingAI}
            isGuest={isGuest}
            onUnlockPrivateMessage={handleUnlockPrivateMessage}
            onUnlockVoiceMessage={handleUnlockVoiceMessage}
          />

          {showMessageLimitBanner ? (
            <ChatQuotaExhaustedBanner
              title={messageLimitTitle}
              ctaLabel={messageLimitCtaLabel}
              onUnlock={handleMessageLimitUnlock}
            />
          ) : (
            <ChatInputBar disabled={!state.historyLoaded} />
          )}
        </div>

        {/* 浏览器提示（应用内浏览器检测） */}
        <BrowserHintOverlay forceShow={isChatDevelopmentEnvironment()} />

        {/* PWA 安装提示触发器（无可见 UI，3.5s 后弹 dialog） */}
        <PwaInstallOverlay />

        <ExternalBrowserDialog
          open={showExternalBrowserDialog}
          onClose={() => setShowExternalBrowserDialog(false)}
          onConfirm={() => void handleOpenExternalBrowser()}
        />

        <HistoryUnlockDialog
          open={state.unlockHistoryPromptVisible}
          lockedCount={state.lockedHistoryCount}
          isLoading={state.isUnlockingHistory}
          errorMessage={state.unlockHistoryError}
          onClose={() => chatDispatch({ type: "ChatUnlockHistoryDismissed" })}
          onConfirm={() => chatDispatch({ type: "ChatUnlockHistoryConfirmed" })}
        />
      </div>
    </MobileShell>
  );
}
