import { Avatar, Button } from '@heroui/react'
import { useEffect, useState } from 'react'
import { ChatAnswerShower } from './ChatAnswerShower'
import { ChatAnswerParser } from './ChatAnswerParser'
import { ChatAnswerRecommend } from './ChatAnswerRecommend'
import { ChatMaxCount } from './ChatMaxCount'
import type { Answer, ChatRecord } from '@/types/chat'
import AvatarBot from '@/assets/avatarBot.png'
import AIIcon from '@/assets/ai-icon.png'
import { useAppDispatch, useAppSelector } from '@/store/hook'
import { setIsAsking } from '@/store/chatSlice'
import type { RootState } from '@/store'
import SdreamLoading from '@/components/SdreamLoading'

interface ChatAnswerBoxProps {
  record: ChatRecord
  showIndex: number
  isLastAnswer: boolean
  index: number
  onSubmitQuestion: (question: string, productCode?: string, workFlowSessionId?: string, recordId?: string) => void
  onRecommendLoadingChange?: (loading: boolean) => void
  onWorkflowSubmit?: (paramMap: Record<string, string>, recordId?: string) => void
  isWorkflowSubmitting?: boolean
  allItems?: ChatRecord[] // 传入整个会话历史，用于查找最后一个 workFlowSessionId
}

export const ChatAnswerBox: React.FC<ChatAnswerBoxProps> = ({ record, showIndex, isLastAnswer, onSubmitQuestion, onRecommendLoadingChange, onWorkflowSubmit, isWorkflowSubmitting, allItems = [] }) => {
  const [isShowRecommend, setIsShowRecommend] = useState(false)
  const [recommendUseAnswer, setRecommendUseAnswer] = useState<Answer>()
  const [innerRecord, setInnerRecord] = useState<ChatRecord>(record)
  const [isTyping, setIsTyping] = useState(false)
  const dispatch = useAppDispatch()
  const isAsking = useAppSelector((state: RootState) => state.chat.isAsking)
  const viteOutputObj = import.meta.env.VITE_OUTPUT_OBJ || 'open'

  const handleTyping = () => {
    setIsTyping(true)
  }

  const handleComplate = (answer: Answer) => {
    setIsShowRecommend(true)
    setRecommendUseAnswer(answer)
    dispatch(setIsAsking(false))
    setIsTyping(false)
  }

  const handleStopTyping = () => {
    const _innerRecord = JSON.parse(JSON.stringify(innerRecord))
    _innerRecord.answerList[showIndex].isStopTyping = true
    setInnerRecord(_innerRecord)
  }

  useEffect(() => {
    setInnerRecord(record)
  }, [record])

  return (
    <div>
      {innerRecord.answerList.map((item, index) => {
        // 当前默认始终展示点赞 / 点踩 / 复制等操作区（是否展示由下层基于卡片类型自行决定）
        const shouldHideOperate = false
        
        // 如果 firstQaFlag 为 true 且存在 workflow 卡片，隐藏整个 chatItem（用户不需要看到这次的结果）
        // 注意：历史记录（isShow === true）不会渲染 CardWorkflowForm，不会自动提交
        // 只有流式返回的新记录（isShow === false）才会渲染 CardWorkflowForm 并执行自动提交
        const hasWorkflowCard = (item.cardList || []).some(attachment => attachment.type === 'card-workflow')
        const shouldHideChatItem = item.firstQaFlag === true && hasWorkflowCard
        
        // 创建包装函数，从会话历史中找到最后一个有 workFlowSessionId 的答案，并在追问时传递
        const handleSubmitQuestionWithWorkflow = (question: string, productCode?: string) => {
          // 从会话历史中找到最后一个有 workFlowSessionId 的答案（从后往前查找）
          let lastWorkFlowSessionId: string | undefined
          let lastRecordId: string | undefined
          for (let i = allItems.length - 1; i >= 0; i--) {
            const historyItem = allItems[i]
            if (historyItem.role === 'ai' && historyItem.answerList?.[0]?.workFlowSessionId) {
              lastWorkFlowSessionId = historyItem.answerList[0].workFlowSessionId
              lastRecordId = historyItem.answerList[0].recordId
              break
            }
          }
          
          // 调用父组件传递的 onSubmitQuestion，传递 workFlowSessionId 和 recordId
          onSubmitQuestion(question, productCode, lastWorkFlowSessionId, lastRecordId)
        }
        
        return (
          index === showIndex && (
            <div 
              className="chatItemBotContainer w-full" 
              key={`${item.recordId}-${index}`}
              style={shouldHideChatItem ? { visibility: 'hidden', height: 0, overflow: 'hidden', margin: 0, padding: 0 } : undefined}
            >
              <div className="flex">
                <Avatar
                  className="sm:mr-[20px] hidden sm:block flex-shrink-0"
                  src={viteOutputObj === 'inner' ? AIIcon : AvatarBot}
                />
                <div
                  style={{ background: '#F7FAFD' }}
                  className="rounded-[20px] box-border px-[16px] py-[12px] sm:px-[24px] sm:py-[20px] relative flex-1 min-w-0"
                >
                  {item.answer?.length || item.cardList?.length
? (
                    <div className="content">
                      {item.isShow && (
                        <ChatAnswerShower
                          onSubmitQuestion={handleSubmitQuestionWithWorkflow}
                          isLastAnswer={isLastAnswer}
                          answer={item}
                          hideOperate={shouldHideOperate}
                          onWorkflowSubmit={onWorkflowSubmit}
                          isWorkflowSubmitting={isWorkflowSubmitting}
                          isAsking={isAsking}
                        />
                      )}
                      {!item.isShow && !item.isChatMaxCount && (
                        <ChatAnswerParser
                          onSubmitQuestion={handleSubmitQuestionWithWorkflow}
                          isLastAnswer={isLastAnswer}
                          isStopTyping={item.isStopTyping}
                          onTyping={handleTyping}
                          onComplate={() => handleComplate(item)}
                          answer={item}
                          hideOperate={shouldHideOperate}
                          onWorkflowSubmit={onWorkflowSubmit}
                          isWorkflowSubmitting={isWorkflowSubmitting}
                          isAsking={isAsking}
                        />
                      )}
                      {!item.isShow && item.isChatMaxCount && <ChatMaxCount />}
                    </div>
                  )
: (
                    <SdreamLoading />
                  )}
                </div>
                <div className="hidden sm:block w-[65px] flex-shrink-0"></div>
              </div>
              {isTyping && (
                <div className="sm:pl-[62px] mt-[12px]">
                  <Button onClick={handleStopTyping} color="primary" variant="bordered">
                    停止生成
                  </Button>
                </div>
              )}

              {isLastAnswer && !item.isChatMaxCount && isShowRecommend && recommendUseAnswer && (
                <ChatAnswerRecommend
                  onSubmitQuestion={(question) => {
                    // 使用 handleSubmitQuestionWithWorkflow，它会从会话历史中查找 workFlowSessionId
                    handleSubmitQuestionWithWorkflow(question)
                  }}
                  answer={recommendUseAnswer}
                  onLoadingChange={onRecommendLoadingChange}
                />
              )}
              <div className="h-[20px] sm:h-[32px] w-full"></div>
            </div>
          )
        )
      })}
    </div>
  )
}
