import React, { LegacyRef } from 'react';
import classNames from 'classnames';
import InputGroup, { InputGroupProps } from './InputGroup';
import { FormDefaults } from '../FormDefaults';

export interface StringInputGroupProps
  extends Omit<
    InputGroupProps<string | undefined | null>,
    'onChange' | 'type' | 'value'
  > {
  type?:
    | 'color'
    | 'email'
    | 'search'
    | 'tel'
    | 'text'
    | 'url'
    | 'password'
    | 'textarea';
}

function StringInputGroup(
  { className, ...rest }: StringInputGroupProps,
  ref: LegacyRef<HTMLInputElement>
) {
  const { input } = rest;

  return (
    <InputGroup
      ref={ref}
      {...rest}
      className={classNames(
        className,
        FormDefaults.cssClassPrefix + 'string-group'
      )}
      value={input.value ?? ''}
      onChange={(e) => {
        if (!e.target.value) {
          input.onChange(undefined);
        } else {
          input.onChange(e.target.value);
        }
      }}
    />
  );
}

/** Standard string input group. */
const StringInputGroupWithRef = React.forwardRef(
  StringInputGroup
) as React.ComponentType<StringInputGroupProps>;

export default StringInputGroupWithRef;
