// Form Input Component
import { InputHTMLAttributes, forwardRef } from 'react';
import { clsx } from 'clsx';
import './FormInput.css';

interface FormInputProps extends InputHTMLAttributes<HTMLInputElement> {
  label?: string;
  error?: string;
  helperText?: string;
}

const FormInput = forwardRef<HTMLInputElement, FormInputProps>(
  ({ label, error, helperText, className, id, ...props }, ref) => {
    const inputId = id || `form-input-${Math.random().toString(36).substring(7)}`;
    const errorId = error ? `${inputId}-error` : undefined;
    const helperId = helperText && !error ? `${inputId}-helper` : undefined;

    return (
      <div className="form-input">
        {label && (
          <label className="form-input__label" htmlFor={inputId}>
            {label}
            {props.required && <span className="form-input__required" aria-label="required">*</span>}
          </label>
        )}
        <input
          ref={ref}
          id={inputId}
          className={clsx('form-input__input', { 'form-input__input--error': error }, className)}
          aria-invalid={!!error}
          aria-describedby={error ? errorId : helperId}
          aria-errormessage={errorId}
          {...props}
        />
        {error && (
          <span id={errorId} className="form-input__error" role="alert">
            {error}
          </span>
        )}
        {helperText && !error && (
          <span id={helperId} className="form-input__helper">
            {helperText}
          </span>
        )}
      </div>
    );
  }
);

FormInput.displayName = 'FormInput';

export default FormInput;

