import Taro from "@tarojs/taro";
import { useEffect, useState, useCallback } from "react";
import { useAppStore } from "@/store/appStore";
export const useKeyboard = (scrollViewRef: React.MutableRefObject<any>, contentId: string, scrollViewId: string ) => {
  
  const [keyboardHeight, setKeyboardHeight] = useState(0);
  const [contentHeight, setContentHeight] = useState(0);
  const [scrollViewHeight, setScrollViewHeight] = useState(0);
  const [updateTrigger, setUpdateTrigger] = useState(0);
  const bottomSafeHeight = useAppStore((state) => state.bottomSafeHeight);
  
  // 计算 marginTopOffset 偏移的距离
  const marginTopOffset = (() => {
    // console.log(contentHeight, keyboardHeight,scrollViewHeight, 9999)
    // 如果内容高度为 0 则将内容高度视频为 容器高度，用于显示最底部的欢迎消息
    const _cotentHeight = contentHeight === 0 ? scrollViewHeight : contentHeight
    if (keyboardHeight <= 0) return 0;
    // 如果内容超过滚动容器，取键盘弹起高度
    if (_cotentHeight >= scrollViewHeight) {
      return -keyboardHeight;
    }
    // 如果内容+键盘弹起高度超过滚动容器, 则取其差值
    if (_cotentHeight + keyboardHeight > scrollViewHeight) {
      // 内容+键盘弹起高度 - 滚动容器高度
      return -(_cotentHeight + keyboardHeight - scrollViewHeight);
    }
    return 0
  })();

  // useEffect(()=> {
  //   console.log('Keyboard state:', keyboardHeight, contentHeight, scrollViewHeight, marginTopOffset)
  // }, [keyboardHeight, contentHeight, scrollViewHeight, marginTopOffset])

  useEffect(() => {
    // 监听键盘高度变化
    // todo: 需要测试是否在键盘弹起时检测内容与容器高度
    Taro.onKeyboardHeightChange((res) => {
      if (res.height <= 0) {
        return setKeyboardHeight(0);
      }
      
      setKeyboardHeight(res.height - bottomSafeHeight + 16);
    });

    return () => {
      setKeyboardHeight(0);
      setScrollViewHeight(0);
      setContentHeight(0)
      // 清理监听器
      Taro.offKeyboardHeightChange();
    };
  }, []);

  // 监听内容高度和 ScrollView 高度变化
  useEffect(() => {
    if (scrollViewRef.current) {
      const query = Taro.createSelectorQuery();
      // 获取滚动容器高度
      query
        .select(scrollViewId)
        .boundingClientRect((rect: any) => {
          if (rect) {
            // console.log('ScrollView height:', rect.height)
            setScrollViewHeight(rect.height);
          }
        })
        .exec();
      // 获取聊天内容高度
      query
        .select(contentId)
        .boundingClientRect((rect: any) => {
          if (rect) {
            // console.log('Content height:', rect.height, scrollViewHeight)
            setContentHeight(rect.height);
          }
        })
        .exec();
    }
  }, [updateTrigger, scrollViewRef.current]);

  // 触发高度重新计算的函数 - 使用 useCallback 稳定引用
  const triggerHeightUpdate = useCallback(() => {
    setUpdateTrigger(prev => prev + 1);
  }, []);


  return {
    marginTopOffset,
    keyboardHeight,
    triggerHeightUpdate,
    setKeyboardHeight,
    setContentHeight,
    setScrollViewHeight,
  }
}