import { useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { Spinner } from '@nextui-org/react'
import { Virtuoso } from 'react-virtuoso'
import { motion } from 'framer-motion'
import { ChatItem } from '../ChatItem'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import { fetchChatRecords } from '@/store/chatSlice'
import type { ChatRecord } from '@/types/chat'

export const ChatContent: React.FC = () => {
  const { id } = useParams<{ id: string }>()
  const dispatch = useAppDispatch()
  const { records, isLoading, error } = useAppSelector(state => state.chat)

  const allItems: ChatRecord[] = [{ type: 'system' }, ...records]

  useEffect(() => {
    if (id) {
      dispatch(fetchChatRecords(id))
    }
  }, [id, dispatch])

  if (isLoading)
    return <div className="w-full h-full flex justify-center"><Spinner /></div>
  if (error) {
    return (
      <div>
        Error:
        {error}
      </div>
    )
  }
  return (
    <motion.div
      initial={{ opacity: 0, y: -50 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{
        duration: 0.4,
        x: { type: 'spring', stiffness: 50 },
        scale: { type: 'spring', stiffness: 50 },
        opacity: { duration: 0.7 },
      }}
      className="w-full h-full mx-auto"
    >
      <Virtuoso
        style={{ height: '100%' }} // 设置一个固定高度或使用动态高度
        data={allItems}
        itemContent={(index, record) => (
          <ChatItem record={record} key={record.originalData?.groupId} />
        )}
        initialTopMostItemIndex={allItems.length - 1} // 初始滚动到底部
        followOutput="smooth" // 新消息时平滑滚动到底部
      />
    </motion.div>
  )
}
