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

export interface PhoneNumberInputGroupProps
  extends Omit<
    InputGroupProps<string | undefined | null>,
    'onChange' | 'type' | 'value'
  > {}

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

  return (
    <InputGroup
      ref={ref}
      autoComplete="tel-national"
      {...rest}
      type="text"
      className={classNames(
        className,
        FormDefaults.cssClassPrefix + 'phone-number-group'
      )}
      value={input.value ?? ''}
      onChange={(e) => {
        if (!e.target.value) {
          input.onChange(undefined);
        } else {
          input.onChange(phoneNumber(e.target.value));
        }
      }}
    />
  );
}

/**A standard phone number input. Will display to the user in `+XXX XXX-XXX-XXXX` format as the number is being inputted.
 * The data will get sent in the same format as displayed. Uses `normalizers.phoneNumber`.
 * @default autoComplete="tel-national"
 */
const PhoneNumberInputGroupWithRef = React.forwardRef(
  PhoneNumberInputGroup
) as React.ComponentType<PhoneNumberInputGroupProps>;

export default PhoneNumberInputGroupWithRef;
