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


class ZipInput extends React.Component {
  constructor() {
    super();
    this.state = {
      value: ''
    };
  }

  /**
   * KeyPress event handler
   */
  onKeyPress(e) {
    this.restrictZip(e);
  }

  /**
   * Paste event handler
   */
  onPaste(e) {
    this.reformatZip(e);
  }

  /**
   * Generic input event handler
   */
  onInput(e) {
    this.reformatZip(e);
  }

  restrictZip(e) {
    const target = e.target;
    const digit = String.fromCharCode(e.which);
    const value = target.value + digit;

    // 12 is plenty big for a postal code
    if (value.length > 12) {
      e.preventDefault();
    }
  }

  reformatZip(e) {
    const target = e.target;
    let value = target.value;

    // Slice characters. 12 is pretty much the largest postal code
    value = value.replace(/\D/g, '').slice(0, 12);
    this.setState({value: value});
    this.props.onStateUpdate({zip: value});
  }

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

    return (
      <div className={fieldClasses}>
        <label className="checkout-field__label">ZIP CODE</label>
        <input className="checkout-field__input"
          type="text"
          autoComplete="cc-zip"
          ref="ZipInput"
          value={value}
          onKeyPress={(e) => this.onKeyPress(e)}
          onPaste={(e) => this.onPaste(e)}
          onInput={(e) => this.onInput(e)}
          disabled={disabled}
        />
        {error ? (<div className="checkout-field__error">{error}</div>) : null}
      </div>
    );
  }
}

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


export default ZipInput;
