import React, { useEffect, useState } from 'react'
import { ChatAnswerAttachment } from './ChatAnswerAttchment'
import { ChatAnswerOperate } from './ChatAnswerOperate'
import { formatMarkdown } from './markdownFormatter'
import type { Answer } from '@/types/chat'
import { MarkdownDetail } from '@/components/MarkdownDetail'
import { fetchTerminateQuestion } from '@/api/chat'

interface ChatAnswerParserProps {
  answer: Answer
  isStopTyping: boolean | undefined
  onTyping: () => void
  onComplate: () => void
}

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

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

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

  const handleStopTyping = async () => {
    const res = await fetchTerminateQuestion(answer)
    if (res.ok) {
      setIsTyping(false)
      onComplate()
    }
  }

  useEffect(() => {
    if (isStopTyping) {
      handleStopTyping()
    }
  }, [isStopTyping])

  return (
    <div className="answerParser">
      <MarkdownDetail>
        {displayedText}
      </MarkdownDetail>
      {!isTyping
      && answer.attachmentList
      && answer.attachmentList?.length !== 0
      && <ChatAnswerAttachment answer={answer} />}

      {!isTyping && <ChatAnswerOperate answer={answer} />}
    </div>
  )
}
