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

export interface NumberInputGroupProps
  extends Omit<
    InputGroupProps<number | undefined | null>,
    'onChange' | 'type' | 'value'
  > {
  /** Custom parsing function when the value changes. */
  parseFunc?: typeof parseInt | typeof parseFloat;
}

function NumberInputGroup(
  { parseFunc, className, ...rest }: NumberInputGroupProps,
  ref: LegacyRef<HTMLInputElement>
) {
  const effectiveParse = parseFunc ?? parseFloat;
  const { input } = rest;

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

/** Standard number input group. By default allows for float values. */
const NumberInputGroupWithRef = React.forwardRef(
  NumberInputGroup
) as React.ComponentType<NumberInputGroupProps>;

export default NumberInputGroupWithRef;
