import React, { useEffect, useMemo, useRef, useState } from 'react'
import { Button } from '@heroui/react'
import { useSearchParams } from 'react-router-dom'
import { CardWorkflowField, type WorkflowFieldItem } from './CardWorkflowField'
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 | 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])

  // 获取 workflow 字段（支持 text/select 等），使用 useMemo 稳定引用
  const workflowFields = useMemo<WorkflowFieldItem[]>(() => {
    return (attachment.content?.fieldList || []).filter(field => Boolean(field?.key) && Boolean(field?.type))
  }, [attachment.content?.fieldList])

  const isFieldValueFilled = (field: WorkflowFieldItem, value: string | string[] | undefined) => {
    if (Array.isArray(value)) {
      return value.length > 0
    }
    return !!value && value.trim() !== ''
  }

  const buildParamValue = (value: string | string[] | undefined) => {
    if (Array.isArray(value)) {
      return value.join(',')
    }
    return value || ''
  }

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

    if (answer.firstQaFlag === true) {
      // 从 URL query 参数中读取值，匹配 fieldList 中的 key
      workflowFields.forEach((field) => {
        const queryValue = searchParams.get(field.key)
        if (field.type === 'select' && field.multiple) {
          initialValues[field.key] = queryValue ? queryValue.split(',').map(item => item.trim()).filter(Boolean) : []
        }
        else {
          initialValues[field.key] = queryValue || ''
        }
      })
    }
    else {
      // 正常初始化，所有字段为空
      workflowFields.forEach((field) => {
        initialValues[field.key] = field.type === 'select' && field.multiple ? [] : ''
      })
    }

    setFormValues(initialValues)
  }, [workflowFields, 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) {
      // 检查是否有字段（workflowFields 不为空）
      if (workflowFields.length === 0) {
        console.log('[CardWorkflowForm] 自动提交：workflowFields 为空，跳过')
        // 更新记录的值
        lastFirstQaFlagRef.current = answer.firstQaFlag
        return
      }

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

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

      if (allRequiredFieldsHaveValues) {
        // 立即设置 hasAutoSubmittedRef，防止重复提交
        hasAutoSubmittedRef.current = true
        // 更新记录的值
        lastFirstQaFlagRef.current = answer.firstQaFlag

        // 构建 paramMap
        const paramMap: Record<string, string> = {}
        workflowFields.forEach((field) => {
          const queryValue = searchParams.get(field.key)
          if (field.type === 'select' && field.multiple) {
            const values = queryValue ? queryValue.split(',').map(item => item.trim()).filter(Boolean) : []
            paramMap[field.key] = values.join(',')
          }
          else {
            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: workflowFields.map(f => ({ key: f.key, label: f.label, required: f.required, value: searchParams.get(f.key), type: f.type })),
        })
        // 更新记录的值
        lastFirstQaFlagRef.current = answer.firstQaFlag
      }
    }
 else {
      // 更新记录的值（即使不执行自动提交，也要更新记录）
      lastFirstQaFlagRef.current = answer.firstQaFlag
    }
    // 移除 onSubmitWorkflow 和 textFields 作为依赖项，使用 useRef 保存引用，避免函数引用变化或 textFields 更新导致重复触发
    // textFields 更新不应该触发重新提交，因为我们已经检查了 firstQaFlag 的变化
  }, [answer.firstQaFlag, isSubmitting, isCompleted, searchParams])

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

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

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

    onSubmitWorkflow(paramMap, recordId, workFlowSessionId)
  }

  const hasRequiredMissing = workflowFields.some(field => field.required && !isFieldValueFilled(field, formValues[field.key]))

  // 检查是否有可渲染字段
  if (workflowFields.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]">
        {workflowFields.map(field => (
          <div key={field.key}>
            <CardWorkflowField
              field={field}
              value={formValues[field.key] ?? (field.type === 'select' && field.multiple ? [] : '')}
              onChange={handleFieldChange}
              disabled={isSubmitting || isCompleted || (answer.firstQaFlag === true && hasAutoSubmittedRef.current)}
            />
          </div>
        ))}
        <Button
          color="primary"
          onPress={handleSubmit}
          isDisabled={isSubmitting || isCompleted || hasRequiredMissing || (answer.firstQaFlag === true && hasAutoSubmittedRef.current)}
          isLoading={isSubmitting}
          className="mt-[8px]"
        >
          {isCompleted ? '已完成' : '提交'}
        </Button>
      </div>
    </div>
  )
}
