import React, { useRef } from 'react'
import { Button } from '@heroui/react'
import type { WorkflowFormField } from '../../lib/workflowCardForm'
import { getWorkflowFieldValidationMessage } from '../../lib/workflowCardForm'

interface CardWorkflowFileFieldProps {
  field: WorkflowFormField
  fileName: string
  disabled: boolean
  isUploading?: boolean
  showRequiredError: boolean
  onPickFile: (file: File) => void
}

export const CardWorkflowFileField: React.FC<CardWorkflowFileFieldProps> = ({
  field,
  fileName,
  disabled,
  isUploading = false,
  showRequiredError,
  onPickFile,
}) => {
  const inputRef = useRef<HTMLInputElement>(null)
  const label = field.required ? `*${field.label}` : field.label
  const displayName = fileName.trim() || '未选择文件'

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file)
      onPickFile(file)
    e.target.value = ''
  }

  return (
    <div>
      <label className="block text-[14px] text-[#4b5563] mb-[6px]">{label}</label>
      <div className="flex items-center gap-[12px] flex-wrap">
        <span className="text-[14px] text-[#6b7280] truncate max-w-full">{displayName}</span>
        <input
          ref={inputRef}
          type="file"
          className="hidden"
          disabled={disabled}
          onChange={handleFileChange}
        />
        <Button
          size="sm"
          variant="bordered"
          color="primary"
          isDisabled={disabled || isUploading}
          isLoading={isUploading}
          onPress={() => inputRef.current?.click()}
        >
          上传文件
        </Button>
      </div>
      {showRequiredError && (
        <p className="text-[12px] text-[#f31260] mt-[6px]">
          {getWorkflowFieldValidationMessage(field)}
        </p>
      )}
    </div>
  )
}
