import React, { useEffect, useRef, 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, workFlowSessionId?: string, recordId?: string) => void
  /** 是否在当前回答中隐藏点赞/点踩/复制按钮（例如策略页自动分析、重新分析） */
  hideOperate?: boolean
  onWorkflowSubmit?: (paramMap: Record<string, string>, recordId?: string) => void
  isWorkflowSubmitting?: boolean
  isAsking?: boolean
}

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, hideOperate, onWorkflowSubmit, isWorkflowSubmitting, isAsking = false }) => {
  const formatAnswer = formatMarkdown(answer.answer || '')
  const [displayedText, setDisplayedText] = useState('')
  const [isTyping, setIsTyping] = useState(false)
  const [hideOperateByCard, setHideOperateByCard] = useState(false)
  const [hasProcessedCardList, setHasProcessedCardList] = useState(false) // 添加标记，避免重复处理cardList
  const completedOnceRef = useRef(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()
  }

  const handleCardListUrls = () => {
    // 如果已经处理过cardList，直接返回，避免重复警告
    if (hasProcessedCardList) {
      return
    }
    if (answer.cardList && answer.cardList.length > 0) {
      const cardsWithUrl = answer.cardList[0].url || ''

      console.log('准备跳转的URL:', cardsWithUrl)
      if (cardsWithUrl) {
        window.open(cardsWithUrl, '_blank')
      }
      else {
        console.warn('cardList中的URL为空')
      }
    }
    else {
      console.warn('cardList为空或不存在')
    }
    setHasProcessedCardList(true) // 标记已处理
  }

  useEffect(() => {
    // Streaming stage: render plain text only (no markdown parsing / no typewriter),
    // to avoid heavy re-rendering and page flicker.
    if (!answer.endAnswerFlag) {
      setDisplayedText(answer.answer || '')
      setIsTyping(false)
      completedOnceRef.current = false
      return
    }
    // Stream ended: render full markdown once (no typewriter) to avoid heavy re-renders.
    if (completedOnceRef.current)
      return
    completedOnceRef.current = true

    // Keep existing contract: notify typing start/end callbacks once.
    onTyping()
    setIsTyping(false)

    if (formatAnswer.includes('<img')) {
      handleImageAnswer()
    }
    else {
      setDisplayedText(formatAnswer)
      onComplate()
    }

    // 流式输出结束时检查 cardList 中的 URL
    handleCardListUrls()
  }, [answer.endAnswerFlag, answer.answer])

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

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

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

  const shouldHideOperate = hideOperateByCard || hideOperate

  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 disablePie={!answer.endAnswerFlag}>
            {displayedText}
          </MarkdownDetail>
        </div>
      )}
      {!isTyping
      && answer.cardList
      && answer.cardList?.length !== 0
      && (
        <ChatAnswerAttachment
          isLastAnswer={isLastAnswer}
          onSubmitQuestion={onSubmitQuestion}
          answer={answer}
          onWorkflowSubmit={onWorkflowSubmit}
          isWorkflowSubmitting={isWorkflowSubmitting}
          isAsking={isAsking}
        />
      )}

      {/* 操作区：仅根据卡片类型 / 上层显式 hideOperate 控制是否展示 */}
      {!isTyping && !shouldHideOperate && <ChatAnswerOperate answer={answer} />}

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