import React, { useEffect, useMemo, useRef, useState } from 'react'
import { Button, Input } from '@heroui/react'
import { useSearchParams } from 'react-router-dom'
import type { Answer, Attachment } from '@/types/chat'

interface CardWorkflowFormProps {
  attachment: Attachment
  answer: Answer
  onSubmitWorkflow: (paramMap: Record<string, string>, recordId?: string, workFlowSeeionId?: string) => void
  isSubmitting?: boolean
  isCompleted?: boolean
}

export const CardWorkflowForm: React.FC<CardWorkflowFormProps> = ({
  attachment,
  answer,
  onSubmitWorkflow,
  isSubmitting = false,
  isCompleted = false,
}) => {
  const [formValues, setFormValues] = useState<Record<string, string>>({})
  const [searchParams] = useSearchParams()
  const hasAutoSubmittedRef = useRef(false) // 防止重复自动提交

  // 获取 text 类型的字段，使用 useMemo 稳定引用
  const textFields = useMemo(() => {
    return attachment.content?.fieldList?.filter(field => field.type === 'text') || []
  }, [attachment.content?.fieldList])

  // 初始化表单值，如果 firstQaFlag 为 true，从 URL query 中读取值
  useEffect(() => {
    const initialValues: Record<string, string> = {}

    if (answer.firstQaFlag === true) {
      // 从 URL query 参数中读取值，匹配 fieldList 中的 key
      textFields.forEach((field) => {
        const queryValue = searchParams.get(field.key)
        initialValues[field.key] = queryValue || ''
      })
    }
 else {
      // 正常初始化，所有字段为空
      textFields.forEach((field) => {
        initialValues[field.key] = ''
      })
    }

    setFormValues(initialValues)
    // 重置自动提交标志，当 firstQaFlag 变化时重新评估
    if (answer.firstQaFlag !== true) {
      hasAutoSubmittedRef.current = false
    }
  }, [attachment, answer.firstQaFlag, searchParams, textFields])

  // 如果 firstQaFlag 为 true，自动提交
  useEffect(() => {
    if (answer.firstQaFlag === true && !hasAutoSubmittedRef.current && !isSubmitting && !isCompleted) {
      // 检查是否所有字段都有值（从 URL query 中读取的）
      const allFieldsHaveValues = textFields.every((field) => {
        const queryValue = searchParams.get(field.key)
        return queryValue && queryValue.trim() !== ''
      })

      if (allFieldsHaveValues) {
        hasAutoSubmittedRef.current = true
        // 构建 paramMap
        const paramMap: Record<string, string> = {}
        textFields.forEach((field) => {
          const queryValue = searchParams.get(field.key)
          paramMap[field.key] = queryValue || ''
        })

        // 获取 recordId 和 workFlowSeeionId（从 answer 中获取，第一次可能没有）
        const recordId = answer.recordId
        const workFlowSeeionId = answer.workFlowSeeionId

        // 延迟一下再提交，确保表单值已经设置完成
        setTimeout(() => {
          onSubmitWorkflow(paramMap, recordId, workFlowSeeionId)
        }, 100)
      }
    }
  }, [answer.firstQaFlag, answer.recordId, answer.workFlowSeeionId, isSubmitting, isCompleted, searchParams, textFields, onSubmitWorkflow])

  const handleInputChange = (key: string, value: string) => {
    setFormValues(prev => ({
      ...prev,
      [key]: value,
    }))
  }

  const handleSubmit = () => {
    // 构建 paramMap
    const paramMap: Record<string, string> = {}
    textFields.forEach((field) => {
      paramMap[field.key] = formValues[field.key] || ''
    })

    // 获取 recordId 和 workFlowSeeionId（从 answer 中获取，第一次可能没有）
    const recordId = answer.recordId
    const workFlowSeeionId = answer.workFlowSeeionId

    onSubmitWorkflow(paramMap, recordId, workFlowSeeionId)
  }

  // 检查是否有 text 类型的字段
  if (textFields.length === 0) {
    return null
  }

  return (
    <div className="card-workflow-form">
      <div className="flex flex-col gap-[12px]">
        {textFields.map(field => (
          <div key={field.key}>
            <Input
              label={field.label}
              value={formValues[field.key] || ''}
              onChange={e => handleInputChange(field.key, e.target.value)}
              isDisabled={isSubmitting || isCompleted || (answer.firstQaFlag === true && hasAutoSubmittedRef.current)}
              variant="bordered"
              className="w-full"
            />
          </div>
        ))}
        <Button
          color="primary"
          onPress={handleSubmit}
          isDisabled={isSubmitting || isCompleted || (answer.firstQaFlag === true && hasAutoSubmittedRef.current)}
          isLoading={isSubmitting}
          className="mt-[8px]"
        >
          {isCompleted ? '已完成' : '提交'}
        </Button>
      </div>
    </div>
  )
}
