// src/pages/Chat/components/ChatItem/ChatAnswerAttchment.tsx
import React, { useState } from 'react'
import { Button, Link } from '@heroui/react'
import { motion } from 'framer-motion'
import { CardWorkflowForm } from './CardWorkflowForm'
import type { Answer, Attachment } from '@/types/chat'
import AnswerProDetailIcon from '@/assets/svg/answerProDetail.svg?react'
import CardNavImg from '@/assets/card-nav.png'
import CardCalculation from '@/assets/card-calculation.png'
import CardDetailImg from '@/assets/card-detail.png'
import CardPlansImg from '@/assets/card-book1111.png'
import CardProductCompareImg from '@/assets/card-product2222.png'
import { fetchDownloadFile } from '@/api/common'
import { FilePreviewModal } from '@/components/FilePreviewModal'

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

export const ChatAnswerAttachment: React.FC<ChatAnswerAttachmentProps> = ({
  answer,
  isLastAnswer,
  onSubmitQuestion,
  onWorkflowSubmit,
  isWorkflowSubmitting = false,
  isAsking: _isAsking = false,
}) => {
  const [previewModalOpen, setPreviewModalOpen] = useState(false)
  const [currentDoc, setCurrentDoc] = useState<any>(null)
  const [docUrl, setDocUrl] = useState<string | undefined>(undefined)

  const handleClickBoxItem = (produceName: string, productCode: string) => {
    if (onSubmitQuestion) {
      // 注意：workFlowSessionId 和 recordId 应该从会话历史中获取，而不是从当前的 answer
      // 这里先传递 undefined，让上层的 handleSubmitQuestionWithWorkflow 来处理
      // 因为 ChatAnswerAttachment 无法访问整个会话历史
      onSubmitQuestion(produceName, productCode)
    }
  }

  const handleClickCard = (attachment: Attachment) => {
    window.open(attachment.content.url)
  }

  const handleClickDocLink = async (doc: any) => {
    try {
      const docId = `${doc.knowledgeName}/${doc.documentStoreKey}`

      const resBlob: any = await fetchDownloadFile(docId)
      const mimeType = blobType(doc.documentAlias) // 修正参数
      const blob = new Blob([resBlob.data], { type: mimeType })

      // 创建 fileBlob URL
      const fileBlobUrl = URL.createObjectURL(blob)

      setCurrentDoc(doc)
      setDocUrl(fileBlobUrl) // 传递 blob URL
      setPreviewModalOpen(true)
    }
    catch (error) {
      console.error('获取文档链接失败:', error)
    }
  }

  function blobType(fileName: string) {
    const ext = fileName.substring(fileName.lastIndexOf('.')).toLowerCase()
    switch (ext) {
      case '.pdf':
        return 'application/pdf'
      case '.doc':
        return 'application/msword'
      case '.docx':
        return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
      case '.xls':
        return 'application/vnd.ms-excel'
      case '.xlsx':
        return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      case '.ppt':
        return 'application/vnd.ms-powerpoint'
      case '.pptx':
        return 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
      case '.txt':
        return 'text/plain;charset=utf-8'
      case '.wps':
        return 'application/wps-office.wps'
      case '.ett':
        return 'application/wps-office.ett'
      default:
        return 'application/octet-stream'
    }
  }

  const closePreviewModal = () => {
    setPreviewModalOpen(false)
    setCurrentDoc(null)
    setDocUrl(null)
  }

  return (
    <>
      <div className="cardList flex flex-col gap-[20px]">
        {answer.cardList
          && answer.cardList.map((attachment, index) => {
            if (attachment?.type) {
              // 使用唯一标识符而不是索引作为 key
              const key = `${attachment.type}_${attachment.id || index}`

              return (
                <div key={key}>
                  {/* 附件：product-detail */}
                  {attachment.type === 'product-detail' && (
                    <div className="bg-[#29B6FD0A] text-[14px] text-primary py-[4px] px-[16px] w-fit flex items-center">
                      <AnswerProDetailIcon />
                      <div className="ml-[6px] max-w-full sm:w-full text-nowrap text-ellipsis overflow-hidden">
                        {attachment.name}
                      </div>
                    </div>
                  )}
                  {/* 附件：引用文件 */}
                  {attachment.type === 'reference'
                    && attachment.content?.docList
                    && attachment.content.docList.length !== 0 && (
                      <div>
                        <p className="text-[14px] text-[#8D9795] mb-[12px]">
                          已为您找到
                          {attachment.content.docList.length}
                          篇资料作为参考：
                        </p>
                        <div className="flex flex-col gap-[9px]">
                          {attachment.content.docList.map(doc => (
                            <Link
                              className="cursor-pointer"
                              onPress={() => handleClickDocLink(doc)}
                              size="sm"
                              key={doc.documentStoreKey}
                              isExternal
                              showAnchorIcon
                              underline="hover"
                            >
                              {doc.documentAlias}
                            </Link>
                          ))}
                        </div>
                      </div>
                    )}
                  {/* 附件：选择 box */}
                  {attachment.type === 'box' && attachment.content.productList.length !== 0 && (
                    <div>
                      <div className="mb-[12px]">{attachment.description}</div>
                      <ul className="flex flex-col gap-[8px]">
                        {attachment.content.productList.map(product => (
                          <motion.li key={product.productCode}>
                            <Button
                              onPress={() => handleClickBoxItem(product.productName, product.productCode)}
                              isDisabled={!isLastAnswer}
                              color="primary"
                              variant="light"
                              className="text-left bg-[#F7FCFF] w-full text-[#333] rounded-[23px] data-[hover=true]:bg-[#E5F6FF] data-[hover=true]:text-primary"
                            >
                              <div className="w-full text-nowrap text-ellipsis overflow-hidden">
                                <span className="ml-[8px]">{product.productName}</span>
                              </div>
                            </Button>
                          </motion.li>
                        ))}
                      </ul>
                    </div>
                  )}
                  {/* 工作流卡片：card-workflow */}
                  {attachment.type === 'card-workflow'
                    && attachment.content?.name === 'form_input'
                    && attachment.content?.fieldList?.some(field => field.type === 'text') && (
                      <CardWorkflowForm
                        key={`workflow-form-${attachment.id || index}-${answer.recordId || 'new'}`}
                        attachment={attachment}
                        answer={answer}
                        onSubmitWorkflow={onWorkflowSubmit || (() => { })}
                        isSubmitting={isWorkflowSubmitting}
                        isCompleted={false}
                      />
                    )}
                  {/* 其他 card-* 类型 */}
                  {attachment.type?.includes('card-') && attachment.type !== 'card-workflow' && (
                    <div onClick={() => handleClickCard(attachment)}>
                      {attachment.type === 'card-nav' && (
                        <img className="w-full max-w-[400px] cursor-pointer" src={CardNavImg} alt="" />
                      )}
                      {attachment.type === 'card-detail' && (
                        <img className="w-full max-w-[400px] cursor-pointer" src={CardDetailImg} alt="" />
                      )}
                      {attachment.type === 'card-calculation' && (
                        <img className="w-full max-w-[400px] cursor-pointer" src={CardCalculation} alt="" />
                      )}
                      {attachment.type === 'card-product-compare' && (
                        <img className="w-full max-w-[400px] cursor-pointer" src={CardProductCompareImg} alt="" />
                      )}
                      {attachment.type === 'card-plans' && (
                        <img className="w-full max-w-[400px] cursor-pointer" src={CardPlansImg} alt="" />
                      )}
                    </div>
                  )}
                </div>
              )
            }
            return null
          })}
      </div>

      {/* 文件预览弹窗 */}
      <FilePreviewModal isOpen={previewModalOpen} onClose={closePreviewModal} doc={currentDoc} docUrl={docUrl} />
    </>
  )
}
