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

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

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

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

/** Input group for inputting money. */
const MoneyInputGroupWithRef = React.forwardRef(
  MoneyInputGroup
) as React.FunctionComponent<MoneyInputGroupProps>;

export default MoneyInputGroupWithRef;
