import React, { useEffect, useState } from 'react'
import { Chip } from '@heroui/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'
import { fetchGetDocumentLinks } from '@/api/common'

interface ChatAnswerParserProps {
  answer: Answer
  isStopTyping: boolean | undefined
  isLastAnswer: boolean
  onTyping: () => void
  onComplate: () => void
  onSubmitQuestion: (question: string, productCode?: string) => void
}

function CheckIcon({ ...props }) {
  return (
    <svg
      fill="none"
      height={18}
      viewBox="0 0 24 24"
      width={18}
      xmlns="http://www.w3.org/2000/svg"
      {...props}
    >
      <path
        d="M12 2C6.49 2 2 6.49 2 12C2 17.51 6.49 22 12 22C17.51 22 22 17.51 22 12C22 6.49 17.51 2 12 2ZM16.78 9.7L11.11 15.37C10.97 15.51 10.78 15.59 10.58 15.59C10.38 15.59 10.19 15.51 10.05 15.37L7.22 12.54C6.93 12.25 6.93 11.77 7.22 11.48C7.51 11.19 7.99 11.19 8.28 11.48L10.58 13.78L15.72 8.64C16.01 8.35 16.49 8.35 16.78 8.64C17.07 8.93 17.07 9.4 16.78 9.7Z"
        fill="currentColor"
      />
    </svg>
  )
}

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

  function extractImageSources(htmlString: string): string[] {
    const imgRegex = /<img[^>]+src="([^">]+)"/gi
    const srcRegex = /src="([^">]+)"/i
    const matches = htmlString.match(imgRegex)

    const sources: string[] = []

    if (matches) {
      matches.forEach((match) => {
        const srcMatch = match.match(srcRegex)
        if (srcMatch && srcMatch[1])
          sources.push(srcMatch[1])
      })
    }

    return sources
  }

  function replaceImageSources(str: string, originalSrcs: string[], newSrcs: string[]): string {
    if (originalSrcs.length !== newSrcs.length)
      return str

    return originalSrcs.reduce((acc, originalSrc, index) => {
      const newSrc = newSrcs[index]
      const regex = new RegExp(originalSrc, 'g')
      return acc.replace(regex, newSrc)
    }, str)
  }

  async function formatImgAnswer(str: string) {
    const imagesSrc = extractImageSources(str)
    const res = await fetchGetDocumentLinks(imagesSrc)
    if (res.data) {
      const arr = replaceImageSources(str, imagesSrc, res.data.map((item: any) => item.docUrl))
      return arr
    }

    else { return replaceImageSources(str, imagesSrc, []) }
  }

  const handleImageAnswer = async () => {
    const res = await formatImgAnswer(formatAnswer)
    setDisplayedText(res)
    setIsTyping(false)
    onComplate()
  }

  useEffect(() => {
    if (isStopTyping) {
      return
    }
    if (!isTyping) {
      onTyping()
      setIsTyping(true)
    }
    if (currentIndex < formatAnswer.length) {
      const nextChar = formatAnswer[currentIndex]
      if (nextChar === '<' || isImageAnswer) {
        setIsImageAnswer(true)
        const timer = setTimeout(() => {
          setCurrentIndex(prevIndex => prevIndex + 1)
        }, 10) // 调整此值以改变打字速度
        return () => clearTimeout(timer)
      }
      else {
        const timer = setTimeout(() => {
          setDisplayedText(formatAnswer.slice(0, currentIndex + 1))
          setCurrentIndex(prevIndex => prevIndex + 1)
        }, 10) // 调整此值以改变打字速度
        return () => clearTimeout(timer)
      }
    }
    else {
      if (answer.endAnswerFlag) {
        if (isImageAnswer) {
          handleImageAnswer()
        }
        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])

  useEffect(() => {
    setHideOperate((answer.cardList || []).some(attachment => attachment?.type === 'box' || attachment?.type?.includes('card-')))
  }, [answer.cardList])

  return (
    <div className="answerParser">

      <div className="mb-[8px]">
        {/* <Chip color="primary" className="mb-[12px]">{answer.step?.message}</Chip> */}
        { answer.step?.step === 'answering' && (
          <Chip color="warning" variant="flat">
            {answer.step?.message}
          </Chip>
        )}
        {answer.step?.step === 'finished' && (
          <Chip color="primary" variant="flat" startContent={<CheckIcon />}>
            {answer.step?.message}
          </Chip>
        )}
      </div>

      {!!displayedText.length && (
        <div style={{ background: '#F7FAFD' }} className={answer.cardList?.length ? 'mb-[20px]' : ''}>
          <MarkdownDetail>
            {displayedText}
          </MarkdownDetail>
        </div>
      )}
      {!isTyping
      && answer.cardList
      && answer.cardList?.length !== 0
      && <ChatAnswerAttachment fromParser isLastAnswer={isLastAnswer} onSubmitQuestion={onSubmitQuestion} answer={answer} />}

      {!isTyping && !hideOperate && <ChatAnswerOperate answer={answer} />}

      {!isTyping && <div className="flex text-[10px] right-[16px] text-[#d0d1d2] bottom-[4px]">AI生成</div>}
    </div>
  )
}
