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, workFlowSessionId?: 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) // 防止重复自动提交
  const lastFirstQaFlagRef = useRef<boolean | undefined>(undefined) // 记录上次的 firstQaFlag 值
  const onSubmitWorkflowRef = useRef(onSubmitWorkflow) // 保存 onSubmitWorkflow 的引用，避免依赖项变化导致重复执行

  // 更新 onSubmitWorkflowRef 的引用
  useEffect(() => {
    onSubmitWorkflowRef.current = onSubmitWorkflow
  }, [onSubmitWorkflow])

  // 获取 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)
  }, [textFields, searchParams, answer.firstQaFlag])

  // 单独处理 firstQaFlag 的变化，重置自动提交标志
  useEffect(() => {
    // 重置自动提交标志，当 firstQaFlag 从 true 变为 false/undefined 时重新评估
    if (answer.firstQaFlag !== true) {
      hasAutoSubmittedRef.current = false
      lastFirstQaFlagRef.current = false // 重置记录的值，确保下次变为 true 时能正确触发
    } else {
      // 如果 firstQaFlag 为 true，初始化 lastFirstQaFlagRef（如果还没有设置）
      // 这样可以处理组件首次渲染时 firstQaFlag 已经是 true 的情况
      if (lastFirstQaFlagRef.current === undefined) {
        lastFirstQaFlagRef.current = false // 设置为 false，让自动提交逻辑能正确触发
      }
    }
  }, [answer.firstQaFlag])

  // 如果 firstQaFlag 为 true，自动提交（仅对流式返回的新记录，历史记录不会渲染此组件）
  useEffect(() => {
    // 如果 firstQaFlag 为 true，尝试自动提交
    // 检查 firstQaFlag 是否从 false/undefined 变为 true（首次变为 true）
    const isFirstQaFlagChangedToTrue = answer.firstQaFlag === true && lastFirstQaFlagRef.current !== true

    // 只在 firstQaFlag 首次变为 true 且尚未自动提交时执行
    if (isFirstQaFlagChangedToTrue && !hasAutoSubmittedRef.current && !isSubmitting && !isCompleted) {
      // 检查是否有字段（textFields 不为空）
      if (textFields.length === 0) {
        console.log('[CardWorkflowForm] 自动提交：textFields 为空，跳过')
        // 更新记录的值
        lastFirstQaFlagRef.current = answer.firstQaFlag
        return
      }

      // 检查是否所有必填字段都有值（从 URL query 中读取的）
      // 只校验 required === true 的字段
      const requiredFields = textFields.filter(field => field.required === true)
      const allRequiredFieldsHaveValues = requiredFields.length === 0 || requiredFields.every((field) => {
        const queryValue = searchParams.get(field.key)
        return queryValue && queryValue.trim() !== ''
      })

      console.log('[CardWorkflowForm] 自动提交检查：', {
        firstQaFlag: answer.firstQaFlag,
        hasAutoSubmitted: hasAutoSubmittedRef.current,
        isSubmitting,
        isCompleted,
        textFieldsCount: textFields.length,
        requiredFieldsCount: requiredFields.length,
        allRequiredFieldsHaveValues,
        requiredFields: requiredFields.map(f => ({ key: f.key, label: f.label })),
        textFields: textFields.map(f => ({ key: f.key, label: f.label, required: f.required })),
      })

      if (allRequiredFieldsHaveValues) {
        // 立即设置 hasAutoSubmittedRef，防止重复提交
        hasAutoSubmittedRef.current = true
        // 更新记录的值
        lastFirstQaFlagRef.current = answer.firstQaFlag
        
        // 构建 paramMap
        const paramMap: Record<string, string> = {}
        textFields.forEach((field) => {
          const queryValue = searchParams.get(field.key)
          paramMap[field.key] = queryValue || ''
        })

        // 获取 recordId 和 workFlowSessionId（从 answer 中获取，第一次可能没有）
        // 注意：这里使用最新的 answer 值，即使依赖项中没有包含它们
        const recordId = answer.recordId
        const workFlowSessionId = answer.workFlowSessionId

        console.log('[CardWorkflowForm] 自动提交：准备提交', { paramMap, recordId, workFlowSessionId })

        // 延迟一下再提交，确保表单值已经设置完成
        const timeoutId = setTimeout(() => {
          console.log('[CardWorkflowForm] 自动提交：执行提交')
          onSubmitWorkflowRef.current(paramMap, recordId, workFlowSessionId)
        }, 100)

        // 清理函数：如果组件卸载或依赖项变化，取消定时器
        return () => {
          clearTimeout(timeoutId)
        }
      } else {
        console.log('[CardWorkflowForm] 自动提交：必填字段值不完整，跳过', {
          requiredFields: requiredFields.map(f => ({ key: f.key, label: f.label, value: searchParams.get(f.key) })),
          allFields: textFields.map(f => ({ key: f.key, label: f.label, required: f.required, value: searchParams.get(f.key) })),
        })
        // 更新记录的值
        lastFirstQaFlagRef.current = answer.firstQaFlag
      }
    } else {
      // 更新记录的值（即使不执行自动提交，也要更新记录）
      lastFirstQaFlagRef.current = answer.firstQaFlag
    }
    // 移除 onSubmitWorkflow 和 textFields 作为依赖项，使用 useRef 保存引用，避免函数引用变化或 textFields 更新导致重复触发
    // textFields 更新不应该触发重新提交，因为我们已经检查了 firstQaFlag 的变化
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [answer.firstQaFlag, isSubmitting, isCompleted, searchParams])

  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 和 workFlowSessionId（从 answer 中获取，第一次可能没有）
    const recordId = answer.recordId
    const workFlowSessionId = answer.workFlowSessionId

    onSubmitWorkflow(paramMap, recordId, workFlowSessionId)
  }

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

  // 如果 firstQaFlag 为 true 且已经自动提交，隐藏表单
  if (answer.firstQaFlag === true && hasAutoSubmittedRef.current) {
    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>
  )
}
