import { useState, useCallback, useEffect, useRef } from 'react';
import { useStore } from 'jotai';
import { msgListAtom } from '@/atoms/im';

interface UseMessageLoadingOptions {
  selectedConversationId: string | null;
  getHistoryMsgActive: (params: {
    conversationId: string;
    endTime: number;
    lastMsgId?: string;
    limit?: number;
  }) => void;
}

interface MessageLoadingState {
  isLoading: boolean;
  hasNextPage: boolean;
  isInitialLoad: boolean;
  canLoadMore: boolean;
  showSkeleton: boolean;
  hasLoadedOnce: boolean;
  hasConfirmedNoHistory: boolean;
  apiCallCount: number;
}

export function useMessageLoading({
  selectedConversationId,
  getHistoryMsgActive,
}: UseMessageLoadingOptions) {
  const store = useStore();
  
  // 合并相关的loading状态
  const [loadingState, setLoadingState] = useState<MessageLoadingState>({
    isLoading: false,
    hasNextPage: true,
    isInitialLoad: true,
    canLoadMore: false,
    showSkeleton: true,
    hasLoadedOnce: false,
    hasConfirmedNoHistory: false,
    apiCallCount: 0,
  });

  // 重置loading状态
  const resetLoadingState = useCallback(() => {
    setLoadingState({
      isLoading: false,
      hasNextPage: true,
      isInitialLoad: true,
      canLoadMore: false,
      showSkeleton: true,
      hasLoadedOnce: false,
      hasConfirmedNoHistory: false,
      apiCallCount: 0,
    });
  }, []);

  // 初始化加载
  const initializeLoading = useCallback(() => {
    if (!selectedConversationId) return;

    const currentMsgList = store.get(msgListAtom);
    const cachedMessages = currentMsgList.get(selectedConversationId) || [];

    resetLoadingState();

    if (cachedMessages.length > 0) {
      // 有缓存：跳过骨架屏和首拉
      setLoadingState(prev => ({
        ...prev,
        isInitialLoad: false,
        showSkeleton: false,
        canLoadMore: true,
        hasLoadedOnce: true,
        hasConfirmedNoHistory: true, // 有缓存说明有历史消息
      }));
      
      if (process.env.NODE_ENV === 'development') {
        console.log('💾 使用缓存消息，跳过骨架与首拉', { count: cachedMessages.length });
      }
      return;
    }

    // 无缓存：显示骨架并首拉
    setLoadingState(prev => ({
      ...prev,
      isInitialLoad: true,
      canLoadMore: false,
      showSkeleton: true,
    }));

    if (process.env.NODE_ENV === 'development') {
      console.log('🦴 无缓存，显示骨架并进行首拉');
    }

    // 执行首次加载
    setTimeout(() => {
      setLoadingState(prev => ({ ...prev, apiCallCount: prev.apiCallCount + 1 }));
      
      if (process.env.NODE_ENV === 'development') {
        console.log('🚀 首拉 API 调用');
      }
      
      getHistoryMsgActive({
        conversationId: selectedConversationId,
        endTime: Date.now(),
        limit: 100,
      });
    }, 100);

    // 超时保护
    const skeletonTimeout = setTimeout(() => {
      setLoadingState(prev => {
        if (prev.showSkeleton && prev.isInitialLoad) {
          if (process.env.NODE_ENV === 'development') {
            console.log('⏰ 骨架屏超时保护触发，强制隐藏');
          }
          return {
            ...prev,
            showSkeleton: false,
            isInitialLoad: false,
            hasLoadedOnce: true,
            canLoadMore: true,
          };
        }
        return prev;
      });
    }, 5000);

    return () => clearTimeout(skeletonTimeout);
  }, [selectedConversationId, getHistoryMsgActive, store, resetLoadingState]);

  // 加载更多历史消息
  const fetchNextPage = useCallback(async () => {
    if (loadingState.isLoading || !loadingState.hasNextPage || !selectedConversationId || !loadingState.canLoadMore) {
      return;
    }
    
    setLoadingState(prev => {
      const newCount = prev.apiCallCount + 1;
      if (process.env.NODE_ENV === 'development') {
        console.log('📊 fetchNextPage 被调用 - API调用次数:', newCount);
      }
      return { ...prev, isLoading: true, apiCallCount: newCount };
    });
    
    try {
      const currentMsgList = store.get(msgListAtom);
      const currentMessages = currentMsgList.get(selectedConversationId) || [];
      const oldestMessage = currentMessages.length > 0 ? currentMessages[0] : null;
      
      const endTime = oldestMessage ? oldestMessage.createTime : Date.now();
      const lastMsgId = oldestMessage ? oldestMessage.messageClientId : undefined;
      
      if (process.env.NODE_ENV === 'development') {
        console.log('📊 fetchNextPage - 加载历史消息:', { endTime, lastMsgId, limit: 20 });
      }
      
      const beforeCount = currentMessages.length;
      
      await getHistoryMsgActive({
        conversationId: selectedConversationId,
        endTime,
        lastMsgId,
        limit: 100,
      });
      
      // 检查是否有新消息加载
      setTimeout(() => {
        const newMsgList = store.get(msgListAtom);
        const newMessages = newMsgList.get(selectedConversationId) || [];
        const afterCount = newMessages.length;
        
        setLoadingState(prev => {
          const updates: Partial<MessageLoadingState> = {};
          
          if (afterCount <= beforeCount) {
            updates.hasNextPage = false;
            
            if (prev.isInitialLoad && afterCount === 0) {
              updates.hasConfirmedNoHistory = false; // 确认没有历史消息
            } else {
              updates.hasConfirmedNoHistory = true; // 有历史消息
            }
            
            if (process.env.NODE_ENV === 'development') {
              console.log('📭 没有更多历史消息', { beforeCount, afterCount });
            }
          }
          
          return { ...prev, ...updates };
        });
      }, 100);
      
    } catch (error) {
      console.error('加载历史消息失败:', error);
      setLoadingState(prev => ({ ...prev, hasNextPage: false }));
    } finally {
      setLoadingState(prev => ({ ...prev, isLoading: false }));
    }
  }, [loadingState.isLoading, loadingState.hasNextPage, loadingState.canLoadMore, selectedConversationId, getHistoryMsgActive, store]);

  // 完成初始加载
  const completeInitialLoad = useCallback((messageCount: number) => {
    setLoadingState(prev => ({
      ...prev,
      showSkeleton: false,
      isInitialLoad: false,
      hasLoadedOnce: true,
      hasConfirmedNoHistory: messageCount === 0 ? false : true,
      canLoadMore: true,
    }));
  }, []);

  return {
    loadingState,
    initializeLoading,
    fetchNextPage,
    completeInitialLoad,
  };
}
