import React from 'react'
import { hasWorkflowFormCards, resolveDisplayAnswerText } from '../../helper'
import type { WorkflowParamMap } from '../../lib/workflowCardForm'
import { formatMarkdown } from './markdownFormatter'
import { ChatAnswerAttachment } from './ChatAnswerAttchment'
import { ChatAnswerOperate } from './ChatAnswerOperate'
import type { Answer } from '@/types/chat'
import { MarkdownDetail } from '@/components/MarkdownDetail'

interface ChatAnswerShowerProps {
  answer: Answer
  isLastAnswer: boolean
  onSubmitQuestion: (question: string, productCode?: string, workFlowSessionId?: string, recordId?: string) => void
  hideOperate?: boolean
  onWorkflowSubmit?: (paramMap: WorkflowParamMap, recordId?: string) => void
  isWorkflowSubmitting?: boolean
  isAsking?: boolean
}

export const ChatAnswerShower: React.FC<ChatAnswerShowerProps> = ({ answer, isLastAnswer, onSubmitQuestion, hideOperate: hideOperateProp, onWorkflowSubmit, isWorkflowSubmitting, isAsking = false }) => {
  const hideOperateByCard = (answer.cardList || []).some(attachment => attachment.type === 'box' || attachment?.type?.includes('card-'))
  const hideOperate = hideOperateByCard || hideOperateProp
  const displayAnswerText = resolveDisplayAnswerText(answer.answer || '')
  const hasCards = Array.isArray(answer.cardList) && answer.cardList.length > 0
  // 历史首包静默记录隐藏卡片；流式/含工作流表单卡片需正常展示
  const shouldRenderCards = hasCards && !(
    answer.isShow === true
    && answer.firstQaFlag === true
    && !hasWorkflowFormCards(answer.cardList)
  )

  return (
    <div className="answerShower">
      {displayAnswerText && (
        <div className={answer.cardList?.length ? 'mb-[12px] sm:mb-[20px]' : ''}>
          <MarkdownDetail>
            {formatMarkdown(displayAnswerText)}
          </MarkdownDetail>
        </div>
      )}
      {/* 历史记录（isShow === true）且 firstQaFlag === true 时，不渲染 ChatAnswerAttachment（避免触发自动提交）
          流式返回的新记录（isShow === false）正常渲染 */}
      {shouldRenderCards && (
        <ChatAnswerAttachment
          onSubmitQuestion={onSubmitQuestion}
          isLastAnswer={isLastAnswer}
          answer={answer}
          onWorkflowSubmit={onWorkflowSubmit}
          isWorkflowSubmitting={isWorkflowSubmitting}
          isAsking={isAsking}
        />
      )}
      {/* 操作区：仅根据卡片类型 / 上层显式 hideOperate 控制是否展示 */}
      {!hideOperate && <ChatAnswerOperate answer={answer} />}
      <div className="flex text-[10px] right-[16px] text-[#d0d1d2] bottom-[4px]">AI生成</div>
    </div>
  )
}
