import React, { useCallback, useEffect, useRef, useState } from 'react'
import { useParams } from 'react-router-dom'
import { Button, Spinner } from '@nextui-org/react'
import { motion } from 'framer-motion'
import { useScroll } from 'ahooks'
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'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import ScrollBtoIcon from '@/assets/svg/scrollBto.svg?react'
import { setIsAsking } from '@/store/chatSlice'

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 scrollableRef = useRef<HTMLDivElement | any>(null)
  const position = useScroll(scrollableRef)

  const handleSubmitQuestion = async (question: string) => {
    dispatch(setIsAsking(true))
    // 添加用户提问的问题
    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,
                    isShow: false,
                    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)
    }
  }, [])

  const scrollToBottom = () => {
    scrollableRef.current.scrollTop = scrollableRef.current.scrollHeight
  }

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

  return (
    <div className={styles.scrollView}>
      <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
              ref={scrollableRef}
              initial={{ opacity: 0, y: -10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{
                duration: 0.3,
                opacity: { duration: 0.1 },
              }}
              className={`${styles.scrollable} scrollbar-hide`}
            >
              <div className={styles.inter}>
                {allItems.map((record, index) => (
                  <div className="w-full chatItem max-w-[1000px] mx-auto" key={index}>
                    {record.role === 'system' && <ChatWelcome />}
                    {record.role === 'user' && <ChatItemUser record={record} />}
                    {record.role === 'ai' && <ChatAnswerBox onSubmitQuestion={handleSubmitQuestion} isLastAnswer={index === allItems.length - 1} showIndex={0} record={record} index={index} />}
                  </div>
                ))}
              </div>
            </motion.div>
          )}
        </div>
        <div className="relative box-border px-[0] mx-auto iptContainer w-full  max-w-[1000px] flex-shrink-0 sm:px-0 pb-[18px]">
          <div className="absolute left-1/2 ml-[-20px] top-[-65px]">
            <motion.div
              initial="hidden"
              animate={(position?.top as number) < -20 ? 'visible' : 'hidden'}
              variants={{
                hidden: { opacity: 0, y: 20, pointerEvents: 'none' as const },
                visible: { opacity: 1, y: 0, pointerEvents: 'auto' as const },
              }}
              transition={{ duration: 0.3, ease: 'easeInOut' }}
            >
              <Button onClick={scrollToBottom} radius="full" isIconOnly color="primary">
                <ScrollBtoIcon />
              </Button>
            </motion.div>
          </div>

          <ChatEditor onSubmit={handleSubmitQuestion} placeholders={RECOMMEND_QUESTIONS_OTHER} />
          <div className="w-full text-center mt-[20px] text-[#3333334d] text-[12px]">
            内容由AI模型生成，其准确性和完整性无法保证，仅供参考
          </div>
        </div>
      </div>
    </div>
  )
}
