import * as React from 'react';

import NumberFormat from 'react-number-format';
import classNames from 'classnames/bind';

import FormElement from 'components/structure/FormElement';
import FieldWrapper from 'components/structure/FieldWrapper';
import { getContent } from 'store/utils/helper';
import { content as localeContent } from 'config/content';

const styles = classNames.bind();

interface InternalProps {
  hideError?: boolean;
  // specific for Number
  suffix?: string;
  decimalSeparator?: string;
  decimalScale?: number;
  thousandSeparator?: string;
  formatNumber?: string;
}

export type NumberInputProps = FormElementProps & FieldWrapperProps & FormItemLabelProps & InternalProps;

interface NumberInputState {}

export default class NumberInput extends React.Component<NumberInputProps, NumberInputState> {
  valueChange = (values: {}) => {
    const { input, formatNumber, onChange } = this.props;

    let newValue;
    if (formatNumber) {
      newValue = values.value;
    } else {
      newValue = values.floatValue;
    }

    if (input?.onChange) input.onChange(newValue);

    if (onChange) onChange(newValue);
  };

  render() {
    const {
      // redux form
      input,
      className,
      formatNumber,
      placeholder,
      mask,
      suffix,
      decimalSeparator,
      decimalScale,
      thousandSeparator,
      fixedDecimalScale,
      allowNegative,
      disabled,
      content,
      lg,
    } = this.props;

    const textPlaceholder = getContent(content, placeholder, lg) || getContent(localeContent, placeholder, lg) || placeholder;

    return (
      <FormElement {...this.props} className={styles('Input', className)}>
        <FieldWrapper {...this.props}>
          <NumberFormat
            disabled={disabled}
            onBlur={input.onBlur}
            onFocus={input.onFocus}
            isNumericString={typeof input.value === 'string'}
            value={input.value}
            onValueChange={this.valueChange}
            placeholder={textPlaceholder}
            mask={mask}
            allowNegative={allowNegative}
            format={formatNumber}
            suffix={suffix}
            decimalSeparator={decimalSeparator}
            decimalScale={decimalScale}
            fixedDecimalScale={fixedDecimalScale}
            thousandSeparator={thousandSeparator}
          />
        </FieldWrapper>
      </FormElement>
    );
  }
}
