'use client'

export interface TextFieldProps {
  label: string
  value?: string
  onChange: (value: string) => void
  required?: boolean
  maxLength?: number
  helpText?: string
  error?: string
}

export function TextField({
  label,
  value = '',
  onChange,
  required,
  maxLength,
  helpText,
  error,
}: TextFieldProps) {
  const charCount = value.length
  const hasError = !!error || (maxLength !== undefined && charCount > maxLength)

  return (
    <div>
      <label className="mb-1 flex items-baseline justify-between text-sm font-medium">
        <span>
          {label}
          {required && <span className="ml-0.5 text-[var(--destructive)]">*</span>}
        </span>
        {maxLength !== undefined && (
          <span
            className={`text-xs ${hasError ? 'text-[var(--destructive)]' : 'text-[var(--muted-foreground)]'}`}
          >
            {charCount}/{maxLength}
          </span>
        )}
      </label>
      <input
        type="text"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        required={required}
        maxLength={maxLength}
        className={`w-full rounded-md border bg-[var(--input-background)] px-3 py-2 text-sm transition-colors outline-none focus:ring-2 focus:ring-[var(--ring)] ${
          hasError ? 'border-[var(--destructive)]' : 'border-[var(--border)]'
        }`}
      />
      {helpText && !error && (
        <p className="mt-1 text-xs text-[var(--muted-foreground)]">{helpText}</p>
      )}
      {error && <p className="mt-1 text-xs text-[var(--destructive)]">{error}</p>}
    </div>
  )
}
