import { useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { Spinner } from '@nextui-org/react'
import { ChatWelcome } from '../ChatWelcome'
import { ChatItem } from '../ChatItem'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import { fetchChatRecords } from '@/store/chatSlice'

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

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

  if (isLoading)
    return <div className="w-full flex justify-center"><Spinner /></div>
  if (error) {
    return (
      <div>
        Error:
        {error}
      </div>
    )
  }
  return (
    <div className="max-w-[1000px] mx-auto box-border py-[32px] flex flex-col gap-[32px]">
      <ChatWelcome />
      {
        records.map((record) => {
          return (
            <ChatItem record={record} key={record.groupId} />
          )
        })
      }
    </div>
  )
}
