import { useMemo, useState, useEffect } from 'react'
import { useAtom, useAtomValue, useStore } from 'jotai'
import { msgListAtom, selectedConversationIdAtom, ExtendedMessage } from '@/atoms/im'

export function useMessageState() {
  const [msgList] = useAtom(msgListAtom)
  const selectedConversationId = useAtomValue(selectedConversationIdAtom)
  const store = useStore()

  // 记录上一次的消息数量，用于检测新消息
  const [lastMessageCount, setLastMessageCount] = useState(0)

  // 使用useMemo优化消息列表计算
  const messages = useMemo(() => {
    const result = selectedConversationId ? msgList.get(selectedConversationId) || [] : []

    if (process.env.NODE_ENV === 'development') {
      console.log('📋 当前消息列表:', selectedConversationId, '消息数量:', result.length)
    }

    return result
  }, [selectedConversationId, msgList])

  // 监听消息数量变化
  useEffect(() => {
    if (process.env.NODE_ENV === 'development') {
      console.log('📈 消息数量变化:', messages.length)
    }
  }, [messages.length])

  // 获取缓存消息
  const getCachedMessages = (conversationId: string): ExtendedMessage[] => {
    const currentMsgList = store.get(msgListAtom)
    return currentMsgList.get(conversationId) || []
  }

  // 分离普通消息和loading消息
  const normalMessages = useMemo(
    () => messages.filter((message) => !message.isLoadingMessage),
    [messages]
  )

  const loadingMessages = useMemo(
    () => messages.filter((message) => message.isLoadingMessage),
    [messages]
  )

  return {
    messages,
    normalMessages,
    loadingMessages,
    selectedConversationId,
    lastMessageCount,
    setLastMessageCount,
    getCachedMessages,
  }
}
