import React, {useState} from 'react';
import {isFloat} from './number';
import {t} from './i18n';

export function AmountField(props) {
  const [errorMessage, setErrorMessage] = useState(null);

  const onCurrencyAmountBlur = (event) => {
    const currencyAmount = event.target.value;
    const {name, onFieldValidate} = props;
    if (isFloat(currencyAmount)) {
      setErrorMessage(null);
      onFieldValidate(name, true);
    } else {
      setErrorMessage(t('t-currency-amount-must-be-number'));
      onFieldValidate(name, false);
    }
  };

  const classes = ['field'];
  let errorDiv = null;
  if (errorMessage !== null) {
    errorDiv = (<div className="field-error">{errorMessage}</div>);
    classes.push('error');
  }

  return (
    <div className="field-area currencyAmount">
      <input className={classes.join(' ')} name={props.name} placeholder={props.placeHolder} maxLength="256" type="text" required onBlur={onCurrencyAmountBlur} />
      {errorDiv}
    </div>
  );
}
