import { useEffect, useRef, useCallback } from 'react';
import { ExtendedMessage } from '@/atoms/im';

interface UseMessageScrollingOptions {
  messages: ExtendedMessage[];
  selectedConversationId: string | null;
  isInitialLoad: boolean;
  showSkeleton: boolean;
  lastMessageCount: number;
  setLastMessageCount: (count: number) => void;
  nim?: any;
}

export function useMessageScrolling({
  messages,
  selectedConversationId,
  isInitialLoad,
  showSkeleton,
  lastMessageCount,
  setLastMessageCount,
  nim,
}: UseMessageScrollingOptions) {
  const containerRef = useRef<HTMLDivElement>(null);

  // 强制滚动到底部的通用函数
  const forceScrollToBottom = useCallback(() => {
    if (containerRef.current) {
      const container = containerRef.current;
      container.scrollTop = container.scrollHeight + 500;
      
      // 使用scrollIntoView作为备用方案
      // const lastElement = container.lastElementChild?.lastElementChild;
      // if (lastElement) {
      //   lastElement.scrollIntoView({ behavior: 'instant', block: "end" });
      // }
    }
  }, []);

  // 延迟滚动到底部（多次尝试确保成功）
  const delayedScrollToBottom = useCallback(() => {
    forceScrollToBottom();
    setTimeout(forceScrollToBottom, 50);
    setTimeout(forceScrollToBottom, 150);
    setTimeout(forceScrollToBottom, 300);
  }, [forceScrollToBottom]);

  // 切换到新会话且存在缓存时，滚动到底部
  useEffect(() => {
    if (!selectedConversationId || !containerRef.current) return;
    
    if (messages.length > 0) {
      delayedScrollToBottom();
    }
  }, [selectedConversationId, messages.length > 0, delayedScrollToBottom]);

  // 骨架屏显示时滚动到底部
  useEffect(() => {
    if (!showSkeleton || !containerRef.current) return;

    const timeoutId = setTimeout(() => {
      if (showSkeleton) {
        delayedScrollToBottom();
        
        if (process.env.NODE_ENV === 'development') {
          console.log('🦴 骨架屏滚动到底部完成');
        }
      }
    }, 200);
    
    return () => clearTimeout(timeoutId);
  }, [showSkeleton, delayedScrollToBottom]);

  // 首次加载完成后滚动到底部
  const handleInitialLoadComplete = useCallback(() => {
    if (messages.length > 0) {
      setTimeout(() => {
        delayedScrollToBottom();
        
        if (process.env.NODE_ENV === 'development') {
          console.log('📨 首次消息加载滚动到底部完成');
        }
      }, 200);
    }
  }, [messages.length, delayedScrollToBottom]);

  // 当有新消息时滚动到底部
  useEffect(() => {
    if (isInitialLoad || !containerRef.current || messages.length === 0) return;
    
    const container = containerRef.current;
    
    // 只有当消息数量增加时才处理滚动
    if (messages.length > lastMessageCount) {
      if (process.env.NODE_ENV === 'development') {
        console.log('📜 检测到新消息，当前消息数:', messages.length, '上次消息数:', lastMessageCount);
      }
      
      // 检查最新的消息是否是用户发送的
      const latestMessage = messages[messages.length - 1];
      const isLatestMessageFromUser = latestMessage && nim ? 
        nim.V2NIMConversationIdUtil.parseConversationTargetId(selectedConversationId || '') !== latestMessage.senderId : false;
      
      const isAtBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 200;
      
      if (process.env.NODE_ENV === 'development') {
        console.log('📜 滚动检查:', {
          isLatestMessageFromUser,
          isAtBottom,
          latestMessageText: latestMessage?.text?.substring(0, 50),
          senderId: latestMessage?.senderId,
          isNewMessage: latestMessage?.isNewMessage
        });
      }
      
      // 改进的滚动策略：
      // 1. 如果是用户发送的消息，总是滚动到底部
      // 2. 如果是新收到的消息（AI回复），总是滚动到底部
      // 3. 如果用户在底部附近，也滚动到底部
      if (isLatestMessageFromUser || latestMessage?.isNewMessage || isAtBottom) {
        if (process.env.NODE_ENV === 'development') {
          console.log('📜 执行滚动到底部，原因:', {
            isUserMessage: isLatestMessageFromUser,
            isNewMessage: latestMessage?.isNewMessage,
            isAtBottom
          });
        }
        setTimeout(() => {
          forceScrollToBottom();
        }, 100);
      }
      
      // 更新消息计数
      setLastMessageCount(messages.length);
    }
  }, [messages.length, isInitialLoad, lastMessageCount, selectedConversationId, nim, forceScrollToBottom, setLastMessageCount]);

  return {
    containerRef,
    forceScrollToBottom,
    delayedScrollToBottom,
    handleInitialLoadComplete,
  };
}
