import React, { useEffect, useState } from 'react'
import ReactMarkdown from 'react-markdown'
import rehypeRaw from 'rehype-raw'
import rehypeSanitize from 'rehype-sanitize'
import remarkGfm from 'remark-gfm'
import { ChatAnswerAttachment } from './ChatAnswerAttchment'
import { ChatAnswerOperate } from './ChatAnswerOperate'
import type { Answer } from '@/types/chat'

interface ChatAnswerParserProps {
  answer: Answer
}

export const ChatAnswerParser: React.FC<ChatAnswerParserProps> = ({ answer }) => {
  const [displayedText, setDisplayedText] = useState('')
  const [currentIndex, setCurrentIndex] = useState(0)
  const [isTyping, setIsTyping] = useState(false)

  useEffect(() => {
    setIsTyping(true)
    if (currentIndex < answer.answer.length) {
      const timer = setTimeout(() => {
        setDisplayedText(answer.answer.slice(0, currentIndex + 1))
        setCurrentIndex(prevIndex => prevIndex + 1)
      }, 10) // 调整此值以改变打字速度

      return () => clearTimeout(timer)
    }
    else {
      setIsTyping(false)
    }
  }, [answer, currentIndex])

  return (
    <div className="answerParser">
      <ReactMarkdown
        rehypePlugins={[rehypeRaw, rehypeSanitize]}
        remarkPlugins={[remarkGfm]}
        className="markdown-content"
      >
        {displayedText}
      </ReactMarkdown>
      {!isTyping && answer.attachmentList?.length !== 0 && <ChatAnswerAttachment answer={answer} />}
      {!isTyping && <ChatAnswerOperate answer={answer} />}
    </div>
  )
}
