import React from 'react';
import classnames from 'classnames';

class PhoneInput extends React.Component {

  // If the page refreshes, make sure we update the parent state
  componentWillReceiveProps(nextProps) {
    if (nextProps.value !== this.props.value) this.props.onStateUpdate({phone: nextProps.value});
  }

  /**
   * onKeyPress event handler
   */
  _restrictInput(e) {
    const digit = String.fromCharCode(e.which);
    const value = e.target.value + digit;

    // Non-numeric not allowed
    if (!/^\d+$/.test(digit)) {
      return;
    }

    // Don't allow more than 20 characters
    if (value.length > 20) {
      e.preventDefault();
    }
  }

  /**
   * onPaste and onChange event handler
   */
  _reformatInput(e) {
    let value = e.target.value;

    // Slice characters. 20 is pretty much the largest postal code
    value = value.replace(/\D/g, '').slice(0, 20);
    this.props.onStateUpdate({phone: value});  // Update parent state
  }

  render() {
    const { disabled, error, value } = this.props;
    const fieldClasses = classnames('checkout-field', 'ccphone', {error: error});

    return (
      <div className={fieldClasses}>
        <label className="checkout-field__label">PHONE</label>
        <input className="checkout-field__input"
          type="text"
          ref="ccPhoneInput"
          value={value}
          onKeyPress={(e) => this._restrictInput(e)}
          onPaste={(e) => this._reformatInput(e)}
          onChange={(e) => this._reformatInput(e)}
          disabled={disabled}
        />
        {error ? (<div className="checkout-field__error">{error}</div>) : null}
      </div>
    );
  }
}

PhoneInput.propTypes = {
  onStateUpdate: React.PropTypes.func,
  error: React.PropTypes.string,
  disabled: React.PropTypes.bool,
  value: React.PropTypes.string
};

export default PhoneInput;
