"use client";

import { useEffect, useMemo } from "react";
import Image from "next/image";
import { useRouter, useSearchParams } from "next/navigation";

import { useAuthDispatch, useAuthState } from "@/stores/auth/auth-context";
import { useChatState } from "@/stores/chat/chat-context";
import { ROUTES } from "@/router/routes";

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

import {
  BrowserHintOverlay,
  ChatArea,
  ChatHeader,
  ChatInputBar,
  ChatInsufficientCreditsBanner,
  ChatUnlockDialogs,
  ExternalBrowserDialog,
  FirstRechargeOfferBanner,
  FullscreenImageViewer,
  PwaInstallOverlay,
} from "./components";
import {
  buildChatImageOverlayUrl,
  buildChatWithoutImageOverlayUrl,
  getChatImageOverlayMessageId,
} from "./chat-image-overlay-url";
import {
  deriveIsGuest,
  isChatDevelopmentEnvironment,
} from "./chat-screen.helpers";
import { useFirstRechargeOfferBanner } from "./hooks/use-first-recharge-offer-banner";
import { useChatUnlockNavigationFlow } from "./hooks/use-chat-unlock-navigation-flow";
import { useChatGuestLogin } from "./hooks/use-chat-guest-login";
import { useChatMessageLimitBanner } from "./hooks/use-chat-message-limit-banner";
import { useExternalBrowserPrompt } from "./hooks/use-external-browser-prompt";
import styles from "./components/chat-screen.module.css";

export function ChatScreen() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const state = useChatState();
  const authState = useAuthState();
  const authDispatch = useAuthDispatch();
  const imageMessageId = getChatImageOverlayMessageId(searchParams);
  const imageReturnUrl = imageMessageId
    ? buildChatImageOverlayUrl(imageMessageId)
    : ROUTES.chat;
  const {
    unlockPaywallRequest,
    requestMessageUnlock,
    closeInsufficientCreditsDialog,
    confirmInsufficientCreditsDialog,
  } = useChatUnlockNavigationFlow({
    returnUrl: ROUTES.chat,
    ignoredKind: "image",
  });
  const {
    unlockPaywallRequest: imageUnlockPaywallRequest,
    requestMessageUnlock: requestImageUnlock,
    closeInsufficientCreditsDialog: closeImageInsufficientCreditsDialog,
    confirmInsufficientCreditsDialog: confirmImageInsufficientCreditsDialog,
  } = useChatUnlockNavigationFlow({
    returnUrl: imageReturnUrl,
    expectedKind: "image",
    expectedMessageId: imageMessageId ?? undefined,
    enabled: imageMessageId !== null,
  });
  const selectedImageMessage = useMemo(
    () =>
      imageMessageId
        ? state.messages.find(
            (item) => item.id === imageMessageId && item.imageUrl,
          ) ?? null
        : null,
    [imageMessageId, state.messages],
  );

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

  // 发送能力由后端统一返回，当前只处理积分不足引导。
  const messageLimitBanner = useChatMessageLimitBanner({
    upgradePromptVisible: state.upgradePromptVisible,
    upgradeReason: state.upgradeReason,
    loginStatus: authState.loginStatus,
  });
  const firstRechargeOfferBanner = useFirstRechargeOfferBanner({
    historyLoaded: state.historyLoaded,
    loginStatus: authState.loginStatus,
  });
  const shouldShowPwaInstall = state.historyLoaded && state.messages.length >= 10;
  const externalBrowserPrompt = useExternalBrowserPrompt({
    hasInitialized: authState.hasInitialized,
    isLoading: authState.isLoading,
    loginStatus: authState.loginStatus,
  });

  useChatGuestLogin({
    dispatch: authDispatch,
    hasInitialized: authState.hasInitialized,
    isLoading: authState.isLoading,
    loginStatus: authState.loginStatus,
  });

  useEffect(() => {
    if (!imageMessageId || !state.historyLoaded || selectedImageMessage) {
      return;
    }
    router.replace(buildChatWithoutImageOverlayUrl(searchParams), {
      scroll: false,
    });
  }, [
    imageMessageId,
    router,
    searchParams,
    selectedImageMessage,
    state.historyLoaded,
  ]);

  function handleUnlockPrivateMessage(messageId: string): void {
    requestMessageUnlock(messageId, "private");
  }

  function handleUnlockVoiceMessage(messageId: string): void {
    requestMessageUnlock(messageId, "voice");
  }

  function handleOpenImage(messageId: string): void {
    router.push(buildChatImageOverlayUrl(messageId), { scroll: false });
  }

  function handleCloseImageViewer(): void {
    router.replace(buildChatWithoutImageOverlayUrl(searchParams), {
      scroll: false,
    });
  }

  function handleUnlockImagePaywall(): void {
    if (!imageMessageId) return;
    requestImageUnlock(imageMessageId, "image");
  }

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

        <div className={styles.layout}>
          {/* isGuest 派生自 auth.loginStatus */}
          <ChatHeader
            isGuest={isGuest}
            offerBanner={
              <FirstRechargeOfferBanner
                visible={firstRechargeOfferBanner.visible}
                discountPercent={firstRechargeOfferBanner.discountPercent}
                onClick={firstRechargeOfferBanner.claim}
                onClose={firstRechargeOfferBanner.close}
              />
            }
          />

          <ChatArea
            messages={state.messages}
            isReplyingAI={state.isReplyingAI}
            isUnlockingMessage={state.isUnlockingMessage}
            unlockingMessageId={state.unlockingMessageId}
            onUnlockPrivateMessage={handleUnlockPrivateMessage}
            onUnlockVoiceMessage={handleUnlockVoiceMessage}
            onOpenImage={handleOpenImage}
          />

          {messageLimitBanner.visible ? (
            <ChatInsufficientCreditsBanner
              title={messageLimitBanner.title}
              description={messageLimitBanner.description}
              ctaLabel={messageLimitBanner.ctaLabel}
              onUnlock={messageLimitBanner.unlock}
            />
          ) : (
            <ChatInputBar disabled={!state.historyLoaded} />
          )}
        </div>

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

        {/* PWA 安装提示触发器（聊天消息数量达到阈值后才允许弹出） */}
        <PwaInstallOverlay enabled={shouldShowPwaInstall} />

        <ExternalBrowserDialog
          open={externalBrowserPrompt.open}
          onClose={externalBrowserPrompt.close}
          onConfirm={() => void externalBrowserPrompt.confirm()}
        />

        <ChatUnlockDialogs
          unlockPaywallRequest={unlockPaywallRequest}
          onCloseInsufficientCreditsDialog={closeInsufficientCreditsDialog}
          onConfirmInsufficientCreditsDialog={confirmInsufficientCreditsDialog}
        />
        <ChatUnlockDialogs
          unlockPaywallRequest={imageUnlockPaywallRequest}
          onCloseInsufficientCreditsDialog={closeImageInsufficientCreditsDialog}
          onConfirmInsufficientCreditsDialog={
            confirmImageInsufficientCreditsDialog
          }
        />

        {selectedImageMessage?.imageUrl ? (
          <FullscreenImageViewer
            messageId={selectedImageMessage.id}
            imageUrl={selectedImageMessage.imageUrl}
            imagePaywalled={selectedImageMessage.imagePaywalled === true}
            isUnlockingImagePaywall={
              state.isUnlockingMessage &&
              state.unlockingMessageId === selectedImageMessage.id
            }
            onUnlockImagePaywall={handleUnlockImagePaywall}
            onClose={handleCloseImageViewer}
          />
        ) : null}
      </div>
    </MobileShell>
  );
}
