'use client';

import ChatMessageList from "./components/ChatMessageList";
import ChatBackground from "./components/ChatBackground";
import ChatMessageAction from "./components/ChatMessageAction";
import ChatDrawers from "./components/ChatDrawers";
import { ChatConfigProvider } from "./context/chatConfig";
import { DrawerLayerProvider } from "./components/ChatDrawers/InlineDrawer";
import { IconButton } from "@/components/ui/button";
import { useSetAtom } from "jotai";
import { isChatProfileDrawerOpenAtom, createDrawerOpenState } from "@/atoms/chat";
import ChatCall from "./components/ChatCall";
import { Badge } from "@/components/ui/badge";
import { RED_DOT_KEYS, useRedDot } from "@/hooks/useRedDot";
import { useS3TokenCache } from "@/hooks/useS3TokenCache";
import { BizTypeEnum } from "@/services/common/types";
import ChatFirstGuideDialog from "./components/ChatFirstGuideDialog";
import CoinInsufficientDialog from "@/components/features/coin-insufficient-dialog";

const ChatPage = () => {
  const setDrawerState = useSetAtom(isChatProfileDrawerOpenAtom);
  const setIsChatProfileDrawerOpen = (open: boolean) => setDrawerState(createDrawerOpenState(open));

  const { hasRedDot } = useRedDot();

  // 预加载S3 Token，提升上传速度
  useS3TokenCache({
    preloadBizTypes: [BizTypeEnum.SOUND_PATH],
    refreshBeforeExpireMinutes: 5
  });

  const handleOpenChatProfileDrawer = () => {
    setIsChatProfileDrawerOpen(true);
  };

  const isShowRedDot = hasRedDot(RED_DOT_KEYS.CHAT_BACKGROUND) || hasRedDot(RED_DOT_KEYS.CHAT_BUBBLE);

  return (
    <ChatConfigProvider>
      <div className="overflow-hidden flex">
        <div className="bg-background-default absolute inset-0" />
        <div className="flex-1 relative transition-all border-t border-solid border-outline-normal">
          <ChatBackground />
          
          {/* 消息列表区域 */}
          <div className="relative h-[calc(100vh-64px)] flex flex-col px-6">
            <ChatMessageList />
            <ChatMessageAction />
            <div className="absolute right-6 top-6 w-8 h-8">
              <IconButton iconfont="icon-icon_chatroom_more" variant="ghost" size="small" onClick={handleOpenChatProfileDrawer} />
              {isShowRedDot && <Badge variant="dot" className="absolute top-0 right-0" />}
            </div>
          </div>
        </div>
        <div className="relative transition-all border-t border-solid border-outline-normal">
          <DrawerLayerProvider>
            <ChatDrawers />
          </DrawerLayerProvider>
        </div>
      </div>
      <ChatCall />

      <ChatFirstGuideDialog />

      <CoinInsufficientDialog />
    </ChatConfigProvider>
  );
}
 
export default ChatPage;