import React, { useEffect, useState } from 'react'
import { Button, Input } from '@heroui/react'
import type { Answer, Attachment } from '@/types/chat'

interface CardWorkflowFormProps {
  attachment: Attachment
  answer: Answer
  onSubmitWorkflow: (paramMap: Record<string, string>, recordId?: 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>>({})

  // 获取 text 类型的字段
  const textFields = attachment.content?.fieldList?.filter(field => field.type === 'text') || []

  // 初始化表单值
  useEffect(() => {
    const initialValues: Record<string, string> = {}
    textFields.forEach((field) => {
      initialValues[field.key] = ''
    })
    setFormValues(initialValues)
  }, [attachment])

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

    onSubmitWorkflow(paramMap, recordId)
  }

  // 检查是否有 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}
              variant="bordered"
              className="w-full"
            />
          </div>
        ))}
        <Button
          color="primary"
          onPress={handleSubmit}
          isDisabled={isSubmitting || isCompleted}
          isLoading={isSubmitting}
          className="mt-[8px]"
        >
          {isCompleted ? '已完成' : '提交'}
        </Button>
      </div>
    </div>
  )
}
