import React from 'react'
import { Input } from '@heroui/react'

export interface WorkflowFieldOption {
  id?: string
  text?: string
  type?: string
}

export interface WorkflowFieldItem {
  key: string
  label: string
  type: string
  required?: boolean
  multiple?: boolean
  options?: WorkflowFieldOption[]
}

interface CardWorkflowFieldProps {
  field: WorkflowFieldItem
  value: string | string[]
  disabled: boolean
  onChange: (key: string, value: string | string[]) => void
}

export const CardWorkflowField: React.FC<CardWorkflowFieldProps> = ({
  field,
  value,
  disabled,
  onChange,
}) => {
  const requiredMark = field.required ? '*' : ''
  const label = `${requiredMark}${field.label}`

  if (field.type === 'select') {
    if (field.multiple) {
      const selectedValues = Array.isArray(value) ? value : []
      return (
        <div>
          <label className="block text-[14px] text-[#4b5563] mb-[6px]">{label}</label>
          <select
            multiple
            value={selectedValues}
            disabled={disabled}
            onChange={(e) => {
              const nextValues = Array.from(e.target.selectedOptions).map(option => option.value)
              onChange(field.key, nextValues)
            }}
            className="w-full min-h-[96px] border border-[#d4d4d8] rounded-[12px] px-[12px] py-[8px] text-[14px] bg-white"
          >
            {(field.options || []).map(option => (
              <option key={option.id || option.text} value={option.id || ''}>
                {option.text || option.id}
              </option>
            ))}
          </select>
        </div>
      )
    }

    const selectedValue = typeof value === 'string' ? value : ''
    return (
      <div>
        <label className="block text-[14px] text-[#4b5563] mb-[6px]">{label}</label>
        <select
          value={selectedValue}
          disabled={disabled}
          onChange={e => onChange(field.key, e.target.value)}
          className="w-full h-[40px] border border-[#d4d4d8] rounded-[12px] px-[12px] text-[14px] bg-white"
        >
          <option value="">
请选择
{field.label}
          </option>
          {(field.options || []).map(option => (
            <option key={option.id || option.text} value={option.id || ''}>
              {option.text || option.id}
            </option>
          ))}
        </select>
      </div>
    )
  }

  return (
    <Input
      label={label}
      value={typeof value === 'string' ? value : ''}
      onChange={e => onChange(field.key, e.target.value)}
      isDisabled={disabled}
      variant="bordered"
      className="w-full"
    />
  )
}
