import React, { useCallback, useEffect, useState } 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 styles from './Chat.module.less'
import { ChatSlogan } from './components/ChatSlogan'
import { ChatMaskBar } from './components/ChatMaskBar'
import { processApiResponse } from './helper'
import { ChatWelcome } from './components/ChatWelcome'
import { ChatItemUser } from './components/ChatItem/ChatItemUser'
import { ChatAnswerBox } from './components/ChatItem/ChatAnswerBox'
import { RECOMMEND_QUESTIONS_OTHER } from '@/config/recommendQuestion'
import { ChatEditor } from '@/components/ChatEditor'
import type { ChatRecord } from '@/types/chat'
import { fetchUserQaRecordPage } from '@/api/conversation'
import { fetchCheckTokenApi, fetchStreamResponse } from '@/api/chat'
import { clearShouldSendQuestion, fetchConversations } from '@/store/conversationSlice'
import type { RootState } from '@/store' // 假设你的 store 文件导出了 RootState 类型
import { useAppDispatch, useAppSelector } from '@/store/hook'

export const Chat: React.FC = () => {
  let ignore = false
  const { id } = useParams<{ id: string }>()
  const [isLoading, setIsLoading] = useState(false)
  const [isNewConversation, setIsNewConversation] = useState(false)
  const [allItems, setAllItems] = useState<ChatRecord[]>([])
  const dispatch = useAppDispatch()
  const shouldSendQuestion = useAppSelector((state: RootState) => state.conversation.shouldSendQuestion)

  const handleSubmitQuestion = async (question: string) => {
    // 添加用户提问的问题
    setAllItems(prevItems => [
      ...prevItems,
      {
        role: 'user',
        question,
      } as ChatRecord,
    ])

    // 检查token
    await fetchCheckTokenApi()

    // 添加一条空的ai问题
    setAllItems(prevItems => [
      ...prevItems,
      {
        role: 'ai',
        answerList: [{}],
      } as ChatRecord,
    ])
    let fetchUrl = `/conversation/api/conversation/mobile/v1/submit_question_stream`
    const proxy = import.meta.env.MODE === 'dev' ? '/api' : '/sdream-api'
    fetchUrl = proxy + fetchUrl

    fetchStreamResponse(
      fetchUrl,
      {
        question,
        conversationId: id,
        stream: true,
      },
      (msg) => {
        if (msg.type === 'DATA') {
          setAllItems((prevItems) => {
            const newItems = [...prevItems] // 创建数组的浅拷贝
            const lastIndex = newItems.length - 1
            if (lastIndex >= 0) {
              // 创建最后一项的新对象，合并现有数据和新的 answer
              newItems[lastIndex] = {
                ...newItems[lastIndex],
                question,
                answerList: [
                  {
                    ...msg.content.data,
                    answer: (newItems[lastIndex].answerList[0].answer || '') + msg.content.data.answer,
                  },
                ],
              }
            }
            return newItems
          })
        }
        if (msg.type === 'END') {
          if (isNewConversation) {
            setTimeout(() => {
              dispatch(fetchConversations())
            }, 2000)
          }
        }
      },
    )
  }

  const getUserQaRecordPage = useCallback(async (conversationId: string) => {
    setIsLoading(true)
    try {
      const res = await fetchUserQaRecordPage(conversationId)
      setIsNewConversation(res.data.length === 0)
      const messages = [{ role: 'system' } as ChatRecord, ...processApiResponse(res.data)]
      setAllItems(messages) // 假设 API 返回的数据结构符合 ChatRecord[]
      if (shouldSendQuestion) {
        handleSubmitQuestion(shouldSendQuestion)
        dispatch(clearShouldSendQuestion())
      }
    }
    catch (error) {
      console.error('Failed to fetch chat records:', error)
      // 可以在这里添加错误处理逻辑
    }
    finally {
      setIsLoading(false)
    }
  }, [])

  useEffect(() => {
    if (id) {
      if (!ignore) {
        getUserQaRecordPage(id)
      }
      return () => {
        ignore = true
      }
    }
  }, [id])

  return (
    <div className={`${styles.chatPage} relative`}>
      <ChatSlogan />
      <ChatMaskBar />
      <div className={styles.content}>
        {isLoading && <div className="w-full h-full flex justify-center"><Spinner /></div>}
        {!isLoading && (
          <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) => (
                <div className="chatItem max-w-[1000px] mx-auto">
                  {record.role === 'system' && <ChatWelcome />}
                  {record.role === 'user' && <ChatItemUser record={record} />}
                  {record.role === 'ai' && <ChatAnswerBox isLastAnswer={index === allItems.length - 1} showIndex={0} record={record} index={index} />}
                </div>
              )}
              initialTopMostItemIndex={allItems.length - 1} // 初始滚动到底部
              followOutput="smooth" // 新消息时平滑滚动到底部
            />
          </motion.div>
        )}
      </div>
      <div className="box-border px-[0] mx-auto iptContainer w-full  max-w-[1000px] flex-shrink-0 sm:px-0 pb-[18px]">
        <ChatEditor onSubmit={handleSubmitQuestion} placeholders={RECOMMEND_QUESTIONS_OTHER} />
        <div className="w-full text-center mt-[20px] text-[#3333334d] text-[12px]">
          内容由AI模型生成，其准确性和完整性无法保证，仅供参考
        </div>
      </div>
    </div>
  )
}
