import { useRef, useEffect, useContext } from "react";
import ChatMessageUserHeader from "./ChatMessageUserHeader";
import CrushLevelAction from "./CrushLevelAction";
import { useUpwardInfiniteScroll } from "@/hooks/useUpwardInfiniteScroll";
import NimMsgContext from "@/context/NimChat/NimMsgContext";
import { useNimChat } from "@/context/NimChat/useNimChat";
import ChatMessageItems from "./ChatMessageItems";
import ChatMessageSkeleton from "./ChatMessageItems/ChatMessageSkeleton";
import { useChatConfig } from "../context/chatConfig";

// 引入我们新创建的自定义Hooks
import { useMessageLoading } from "../hooks/useMessageLoading";
import { useMessageScrolling } from "../hooks/useMessageScrolling";
import { useMessageState } from "../hooks/useMessageState";
import { useCrushLevelAction } from "../hooks/useCrushLevelAction";
import ChatPrologueMessage from "./ChatPrologueMessage";

const ChatMessageList = () => {
  // 获取NIM相关的Context
  const { nim } = useNimChat();
  const { getHistoryMsgActive } = useContext(NimMsgContext);
  const { aiId } = useChatConfig();
  
  // 用于引用ChatMessageUserHeader的ref
  const userHeaderRef = useRef<HTMLDivElement>(null);

  // 使用消息状态Hook
  const {
    messages,
    normalMessages,
    loadingMessages,
    selectedConversationId,
    lastMessageCount,
    setLastMessageCount,
  } = useMessageState();

  // 使用加载状态Hook
  const {
    loadingState,
    initializeLoading,
    fetchNextPage,
    completeInitialLoad,
  } = useMessageLoading({
    selectedConversationId,
    getHistoryMsgActive,
  });

  // 使用滚动Hook
  const {
    containerRef,
    handleInitialLoadComplete,
  } = useMessageScrolling({
    messages,
    selectedConversationId,
    isInitialLoad: loadingState.isInitialLoad,
    showSkeleton: loadingState.showSkeleton,
    lastMessageCount,
    setLastMessageCount,
    nim,
  });

  // 使用CrushLevelAction Hook
  const { showCrushLevelAction } = useCrushLevelAction({
    containerRef,
    userHeaderRef,
  });

  // 注意：旧的开场白消息发送逻辑已被移除，现在使用 ChatPrologueMessage 组件来持久化显示开场白

  // 使用向上滚动的无限滚动Hook
  const { loadMoreRef } = useUpwardInfiniteScroll({
    hasNextPage: loadingState.hasNextPage,
    isLoading: loadingState.isLoading,
    fetchNextPage,
    threshold: 800,
    enabled: loadingState.canLoadMore && loadingState.hasNextPage,
    containerRef, // 传入正确的容器ref
  });

  // 初始化加载
  useEffect(() => {
    initializeLoading();
  }, [initializeLoading]);

  // 首次加载完成后的处理
  useEffect(() => {
    if (loadingState.isInitialLoad && (messages.length > 0 || loadingState.apiCallCount > 0)) {
      if (process.env.NODE_ENV === 'development') {
        console.log('📨 检测到首批消息加载完成，准备隐藏骨架屏', {
          messagesLength: messages.length,
          apiCallCount: loadingState.apiCallCount
        });
      }
      
      // 延迟处理，确保平滑过渡
      setTimeout(() => {
        completeInitialLoad(messages.length);
        handleInitialLoadComplete();
        
        if (process.env.NODE_ENV === 'development') {
          console.log('🦴 隐藏骨架屏，显示真实消息');
        }
      }, 200);
    }
  }, [messages.length, loadingState.isInitialLoad, loadingState.apiCallCount, completeInitialLoad, handleInitialLoadComplete]);

  console.log('messages', messages, selectedConversationId, nim?.V2NIMConversationIdUtil.parseConversationTargetId(selectedConversationId || ''));

  return (
    <div 
      ref={containerRef}
      className="flex-1 min-h-0 overflow-y-auto pt-12 pb-20"
    >
      <div className="max-w-[752px] mx-auto">
        {/* 用户信息头部始终显示在顶部 */}
        <div ref={userHeaderRef}>
          <ChatMessageUserHeader />
        </div>

        {/* 隐藏的加载更多触发器 - 在用户头部后面 */}
        {loadingState.hasNextPage && loadingState.canLoadMore && (
          <div
            ref={loadMoreRef}
            className="h-1 w-full opacity-0"
            style={{ backgroundColor: 'red' }} // 临时调试样式，方便查看位置
          />
        )}

        {/* 显示加载骨架屏当正在加载更多消息且用户滚动到顶部附近时 */}
        {loadingState.hasNextPage && loadingState.isLoading && (
          <div className="mt-4">
            <ChatMessageSkeleton />
          </div>
        )}
        
        {/* CrushLevelAction - 使用visibility和opacity控制显示/隐藏，避免图片重复加载 */}
        <div 
          style={{ 
            visibility: showCrushLevelAction ? 'visible' : 'hidden',
            opacity: showCrushLevelAction ? 1 : 0,
            pointerEvents: showCrushLevelAction ? 'auto' : 'none',
            transition: 'opacity 0.2s ease-in-out'
          }}
        >
          <CrushLevelAction />
        </div>
        
        {/* 骨架屏 - 仅在首次访问且无数据且尚未完成加载时显示 */}
        {loadingState.showSkeleton && messages.length === 0 && loadingState.isInitialLoad && !loadingState.hasLoadedOnce && (
          <ChatMessageSkeleton />
        )}
        
        {/* 消息列表 */}
        {!loadingState.showSkeleton && (
          <div className="space-y-4 mt-8">
            {/* 持久化开场白 - 始终显示在消息列表顶部 */}
            <ChatPrologueMessage />
            
            {/* 普通消息 */}
            {normalMessages.map((message) => {
              // 判断是否是用户发送的消息（根据发送者ID）
              const isUser = !message.senderId.includes(aiId.toString());
              
              return (
                <div key={message.messageClientId || message.messageServerId}>
                  <ChatMessageItems 
                    isUser={isUser}
                    message={message}
                  />  
                </div>
              );
            })}
            
            {/* Loading消息，始终显示在最后 */}
            {loadingMessages.map((message) => (
              <div key={message.messageClientId}>
                <ChatMessageItems 
                  isUser={false}
                  message={message}
                />  
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
 
export default ChatMessageList;