import { useEffect, useRef } from 'react';
import { useTextChat } from '@/store/textChatStore';
import { useKeyboard } from '../components/keyboard';

/**
 * 聊天滚动管理 Hook
 * 负责处理滚动相关的逻辑，包括自动滚动、键盘适配等
 */
export const useChatScrollManager = (messagesLength: number, pageIndex: number, loadMore?: () => void): {
  scrollViewRef: React.MutableRefObject<any>;
  scrollTop: number;
  keyboardHeight: number;
  marginTopOffset: number;
  handleScrollToUpper: () => void;
  handleTouchMove: () => void;
  handleScrollToLower: () => void;
  setScrollTop: (num?: number) => void;
  setAutoScroll: (b: boolean) => void;
} => {
  const scrollViewRef = useRef<any>(null);
  const initialScrolledRef = useRef(false);
  const prevLengthRef = useRef(messagesLength);

  const { setScrollTop, setAutoScroll } = useTextChat();
  const scrollTop = useTextChat((state) => state.scrollTop);

  // 键盘高度管理
  const { keyboardHeight, marginTopOffset, triggerHeightUpdate } = useKeyboard(
    scrollViewRef,
    "#messageList",
    "#scrollView"
  );

  // 首次进入界面滚动到底部
  useEffect(() => {
    console.log('useEffect 首次进入界面滚动到底部: ', pageIndex, messagesLength, initialScrolledRef.current)
    // 仅首次 pageIndex === 1 且已经有消息时滚动一次
    if (pageIndex === 1 && messagesLength > 0 && !initialScrolledRef.current) {
      initialScrolledRef.current = true;

      // 延迟1秒再滚动，确保 DOM 已完成渲染
      setTimeout(() => {
        setScrollTop(999999);
        console.log("首次进入，滚动到底部");
      }, 800);
    }
  }, [pageIndex, messagesLength, setScrollTop]);

  // 监听消息列表变化，触发键盘高度重新计算
  useEffect(() => {
    // 只在长度真正变化时才触发
    if (prevLengthRef.current !== messagesLength) {
      prevLengthRef.current = messagesLength;

      // 使用 setTimeout 确保 DOM 更新完成后再计算高度
      const timer = setTimeout(() => {
        triggerHeightUpdate();
      }, 100);

      return () => clearTimeout(timer);
    }
  }, [messagesLength, triggerHeightUpdate]);

  // 滚动事件处理
  const handleScrollToUpper = () => {
    console.log("onscroll");
    loadMore?.();
  };

  const handleTouchMove = () => {
    console.log("set auto scroll false");
    setAutoScroll(false);
  };

  const handleScrollToLower = () => {
    setAutoScroll(true);
  };

  return {
    // refs
    scrollViewRef,
    
    // 滚动相关状态
    scrollTop,
    keyboardHeight,
    marginTopOffset,
    
    // 事件处理函数
    handleScrollToUpper,
    handleTouchMove,
    handleScrollToLower,
    
    // 工具方法
    setScrollTop,
    setAutoScroll,
  };
};
