import type { InputHTMLAttributes, ReactNode } from 'react';

export interface FieldProps extends InputHTMLAttributes<HTMLInputElement> {
  label: string;
  error?: string | null;
  hint?: string;
  action?: ReactNode;
}

export function Field({
  label,
  error,
  hint,
  action,
  className,
  id,
  ...props
}: FieldProps) {
  const inputId = id ?? `field-${label.toLowerCase().replace(/\s+/g, '-')}`;
  const helpId = `${inputId}-help`;

  return (
    <label className={`ui-field ${className ?? ''}`.trim()} htmlFor={inputId}>
      <span className="ui-field-label">{label}</span>
      <div className="ui-field-row">
        <input
          {...props}
          id={inputId}
          aria-invalid={Boolean(error)}
          aria-describedby={error || hint ? helpId : undefined}
        />
        {action}
      </div>
      {error || hint ? <span id={helpId} className={`ui-field-help ${error ? 'is-error' : ''}`.trim()}>{error ?? hint}</span> : null}
    </label>
  );
}

