import { Text, View } from "tamagui";
import { CustomSafeArea } from "@/components/common/CustomSafeArea";
import { CustomHeader } from "@/components/common/CustomHeader";
import { useEffect, useCallback, useRef, useMemo, memo } from "react";
import { useFocusEffect } from "@react-navigation/native";
import { useChatWsSocketStore } from "@/stores";
import wsConnect from "@/services/websocket";
import { FlatList, StyleSheet } from "react-native";
import { useSessionListStore, useSessionStore } from "@/stores";
import CustomAvatar from "@/components/ui/CustomAvatar";
import { beautifyTime } from "@/utils/time/formatDateTime";
import { router } from "expo-router";

// 在组件外部定义JSX元素，避免每次渲染都创建
const headerLeftElement = <Text>我是左边</Text>;
const headerRightElement = <Text>我是右边</Text>;

// 会话列表项-使用memo优化
const SessionItem = memo(({ item }: { item: any }) => {
  // 跳转会话详情
  const toSessionDetail = () => {
    useSessionStore.setState({ session: item });
    router.push("/chat/sessionDetail");
  };
  return (
    <View style={chatTabStyle.sessionItem} onPress={toSessionDetail}>
      <CustomAvatar
        mode={item.group_type === 0 ? 1 : 2}
        userName={item.name}
        avatar={item.avatar}
        groupType={item.group_type}
      />
      <View style={chatTabStyle.sessionInfo}>
        <View style={chatTabStyle.sessionInfoHeader}>
          <Text style={chatTabStyle.sessionInfoHeaderName}>{item.name}</Text>
          <Text style={chatTabStyle.sessionInfoHeaderTime}>
            {/* {beautifyTime(item.updated_at)} */}
            {item.updated_at}
          </Text>
        </View>
        <View style={chatTabStyle.sessionInfoContent}>
          <Text style={chatTabStyle.sessionInfoContentText}>
            {item.msg_text}
          </Text>
        </View>
      </View>
    </View>
  );
});

export default function ChatScreen() {
  // 聊天 websocket
  const { connectionState } = useChatWsSocketStore();

  // 使用ref存储最新的connectionState，避免闭包陷阱
  const connectionStateRef = useRef(connectionState);
  connectionStateRef.current = connectionState;

  // 是否是第一次进入页面
  const isFirstEnter = useRef(true);
  // 是否正在断开连接
  const isDisconnecting = useRef(false);
  // 是否等待重连
  const isPendingReconnect = useRef(false);

  // 监听 tab 页面焦点变化
  useFocusEffect(
    useCallback(() => {
      // tab 获得焦点时执行（进入页面）
      const handleConnection = async () => {
        console.log("进入聊天页面", connectionStateRef.current);
        if (
          connectionStateRef.current === "disconnected" ||
          connectionStateRef.current === "error"
        ) {
          // 连接websocket
          try {
            await wsConnect.connect(); // 正确等待Promise
          } catch (error) {
            console.error("WebSocket 连接失败:", error);
            // 连接失败不阻塞UI，让重连机制自动处理
          }
        } else if (isDisconnecting.current) {
          // 正在断开上次连接，需等待断开完成后自动重连
          isPendingReconnect.current = true;
        }
      };

      handleConnection();

      return () => {
        // tab 失去焦点时执行（离开页面）
        console.log("离开聊天页面");
        isDisconnecting.current = true;
        wsConnect.disconnect();
      };
    }, []) // 保持空依赖数组，通过ref获取最新状态
  );

  // 监听 websocket 连接状态
  useEffect(() => {
    if (isFirstEnter.current) {
      // 第一次进入还未发生状态变化，不执行
      isFirstEnter.current = false;
      return;
    }
    if (connectionState === "connected") {
      console.log("WebSocket 已连接！"); // 发送测试消息
      // 连接成功，重置所有标志
      if (isDisconnecting.current) {
        isDisconnecting.current = false;
      }
      if (isPendingReconnect.current) {
        isPendingReconnect.current = false;
      }
      // 这里连接成功可能服务端还没确认连接成功，所以不能执行后续业务
      // 考虑在服务端确认连接成功后，再执行后续业务
      // wsConnect.emit("test", { message: "Hello from login page!" });
    } else {
      if (connectionState === "connecting") {
        console.log("开始连接 WebSocket...");
      } else if (connectionState === "disconnected") {
        console.log("WebSocket 已断开！");
        isDisconnecting.current = false;
        if (isPendingReconnect.current) {
          console.log("检测到等待重连，开始重连");
          isPendingReconnect.current = false; // 重置标志
          // 重连 websocket
          wsConnect.connect();
        }
      } else if (connectionState === "reconnecting") {
        console.log("WebSocket 重新连接中...");
      } else if (connectionState === "error") {
        console.log("WebSocket 连接错误");
        // 连接错误时也要重置标志，避免死循环
        if (isDisconnecting.current) {
          isDisconnecting.current = false;
        }
        if (isPendingReconnect.current) {
          isPendingReconnect.current = false;
        }
      }
    }
  }, [connectionState]);

  // 会话列表
  const { sessionList, fetchSessionList } = useSessionListStore();

  //组件挂载
  useEffect(() => {
    fetchSessionList();
  }, []);

  // 组件卸载清理
  useEffect(() => {
    return () => {
      // 组件卸载时确保断开连接
      wsConnect.disconnect();
    };
  }, []);

  // renderItem 函数-使用useCallback优化
  const renderSessionItem = useCallback(({ item }: { item: any }) => {
    return <SessionItem item={item} />;
  }, []);

  // keyExtractor 函数-使用useCallback优化
  const keyExtractor = useCallback((item: any) => item.id, []);

  // 缓存 FlatList 的样式和配置
  const flatListProps = useMemo(
    () => ({
      style: chatTabStyle.sessionList,
      data: sessionList,
      keyExtractor,
      renderItem: renderSessionItem,
      // 性能优化配置
      removeClippedSubviews: true, // 移除屏幕外的子视图
      maxToRenderPerBatch: 10, // 每批渲染的最大项目数
      windowSize: 10, // 渲染窗口大小
      initialNumToRender: 10, // 初始渲染项目数
      getItemLayout: undefined, // 如果知道项目高度，可以优化此项
    }),
    [sessionList, keyExtractor, renderSessionItem]
  );

  //聊天Tab自定义导航栏
  //导航栏左侧 - 优化：返回预定义的JSX元素
  const ChatTabHeaderLeft = useCallback(() => {
    return headerLeftElement;
  }, []);
  //导航栏右侧 - 优化：返回预定义的JSX元素
  const ChatTabHeaderRight = useCallback(() => {
    return headerRightElement;
  }, []);

  return (
    <CustomSafeArea>
      <CustomHeader
        headerShown={true}
        leftContent={ChatTabHeaderLeft()}
        centerContent={""}
        rightContent={ChatTabHeaderRight()}
      />
      <FlatList {...flatListProps} />
    </CustomSafeArea>
  );
}

const chatTabStyle = StyleSheet.create({
  sessionList: {
    marginHorizontal: 16,
    marginTop: 16,
    backgroundColor: "#fff",
  },
  sessionItem: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "flex-start",
    gap: 10,
    paddingVertical: 14,
    marginHorizontal: 8,
    borderBottomWidth: 1,
    borderBottomColor: "#F1F1F1",
  },
  sessionInfo: {
    flex: 1,
    gap: 3,
  },
  sessionInfoHeader: {
    flexDirection: "row",
    alignItems: "flex-start",
    justifyContent: "space-between",
  },
  sessionInfoHeaderName: {
    fontSize: 16,
    lineHeight: 22,
    fontFamily: "Bold",
    color: "#191919",
    flex: 1,
    flexWrap: "wrap",
  },
  sessionInfoHeaderTime: {
    fontSize: 14,
    lineHeight: 22,
    fontFamily: "Medium",
    color: "#BDBDBD",
    flexShrink: 0,
    paddingVertical: 1.5,
  },
  sessionInfoContent: {},
  sessionInfoContentText: {
    fontSize: 14,
    lineHeight: 20,
    color: "#999999",
  },
});
