import React from 'react';
import classnames from 'classnames';
import { restrictNumeric, hasTextSelected } from 'components/payment/utils'

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

  /**
   * KeyPress event handler
   */
  onKeyPress(e) {
    utils.restrictNumeric(e);
    this.restrictCVC(e);
  }

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

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

  /**
   * Ensures we're only typing specific numeric patterns.
   * @param  {Object} e HTML event
   */
  restrictCVC(e) {
    const target = e.target;
    const digit = String.fromCharCode(e.which);
    const value = target.value + digit;

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

    // No text selections
    if (utils.hasTextSelected(target)) {
      return true;
    }

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

  /**
   * Simple reformatter for inputted CVCs
   * @param  {[type]} e [description]
   * @return {[type]}   [description]
   */
  reformatCVC(e) {
    const target = e.target;
    let value = target.value;

    // Slice characters
    value = value.replace(/\D/g, '').slice(0, 4);
    this.setState({value: value});
    this.props.onStateUpdate({cvc: value});  // Update parent state
  }

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

    return (
      <div className={fieldClasses}>
        <label className="checkout-field__label">CVC</label>
        <input className="checkout-field__input"
          type="text"
          autoComplete="cc-cvv"
          ref="ccCVCInput"
          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>
    );
  }
}

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

export default CVCInput;
