import { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import { View } from "@tarojs/components";
import { useAppStore } from '@/store/appStore';
import { useTextChat } from '@/store/textChatStore';

/**
 * 聊天UI状态管理 Hook
 * 负责处理UI相关的状态，如欢迎页显示、背景设置、输入框高度等
 */
export const useChatUI = (
  agent: any,
  historyListLength: number,
  messageListLength: number
): {
  showWelcome: boolean;
  haveBg: boolean;
  inputContainerHeight: number;
  inputContainerBottomOffset: number;
  setShowWelcome: (show: boolean) => void;
  getBgContent: () => string;
  createNavLeftRenderer: (PersonalCard: any, IconArrowLeftWhite24: any, IconArrowLeft: any) => () => JSX.Element;
} => {
  const [showWelcome, setShowWelcome] = useState(!historyListLength);
  const [inputContainerHeight, setInputContainerHeight] = useState(0);
  // const scrollTop = useTextChat((state)=> state.scrollTop)

  const bottomSafeHeight = useAppStore((state) => state.bottomSafeHeight);

  // 判断是否有背景
  const haveBg = !!agent?.enabledChatBg && !!agent.avatarUrl?.length;

  // 计算输入框底部偏移量
  // 针对没有 safeArea?.bottom 的手机，需要额外增加 12 高度
  const inputContainerBottomOffset = bottomSafeHeight <= 0 ? 12 : 0;

  // 获取背景内容
  const getBgContent = () => {
    if (!agent?.avatarUrl || !agent?.enabledChatBg) {
      return "";
    }
    return agent?.avatarUrl;
  };

  // 渲染导航栏左侧内容的工厂函数
  const createNavLeftRenderer = (PersonalCard: any, IconArrowLeftWhite24: any, IconArrowLeft: any) => {
    return () => {
      return (
        <View
          className="flex items-center gap-8"
          onClick={() => Taro.navigateBack()}
        >
          {haveBg ? <IconArrowLeftWhite24 /> : <IconArrowLeft />}
          <PersonalCard agent={agent} haveBg={haveBg} />
          {/* {scrollTop} */}
        </View>
      );
    };
  };

  // 是否显示欢迎UI
  useEffect(() => {
    setShowWelcome(!messageListLength && !historyListLength);
  }, [historyListLength, messageListLength]);

  // 设置导航栏颜色
  useEffect(() => {
    if (haveBg) {
      Taro.setNavigationBarColor({
        frontColor: "#ffffff",
        backgroundColor: "transparent",
      });
    }
    return () => {
      Taro.setNavigationBarColor({
        frontColor: "#000000",
        backgroundColor: "transparent",
      });
    };
  }, [haveBg]);

  // 计算输入框容器高度
  useEffect(() => {
    const query = Taro.createSelectorQuery();
    query
      .select("#inputContainer")
      .boundingClientRect((rect: any) => {
        if (rect) {
          setInputContainerHeight(rect.height - bottomSafeHeight);
        }
      })
      .exec();
  }, [agent, bottomSafeHeight]);

  return {
    // 状态
    showWelcome,
    haveBg,
    inputContainerHeight,
    inputContainerBottomOffset,

    // 设置方法
    setShowWelcome,

    // 工具方法
    getBgContent,
    createNavLeftRenderer,
  };
};
