import classNames from 'classnames';
import debounce from 'lodash.debounce';
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';

import { ENTER, ESCAPE, DELETE } from '../../constants';

const defaultProps = {
  isChickletNone: false,
  hasInitialValues: false,
  onSelectionClearSelectedValueFromTextbox: true,
}

const propTypes = {
  setSelectedItems: PropTypes.func,
  isChickletNone: PropTypes.bool,
  hasInitialValues: PropTypes.bool,
  lastInitialValue: PropTypes.object,
  placeholderTextLabel: PropTypes.string,
  handleRemove: PropTypes.func,
}

class InputString extends React.Component {

  constructor(props) {
    super(props);

    this.handleKeyUp = this.handleKeyUp.bind(this);
    this.renderInput = this.renderInput.bind(this);
    this.addItem = this.addItem.bind(this);
    this.delayedAddItem = debounce(this.addItem, 0);
  }

  initialInputValue(){
    if (this.props.isChickletNone && this.props.hasInitialValues) {
      return this.props.lastInitialValue.label;
    }
  }

  setInputValue(value){
    if (this.inputString != null ) {
      this.inputString.value = value || '';
    }
  }

  addItem(value) {
    this.props.addItem({ value, customOperator: 'Like' });
    if (this.props.isChickletNone) {
      this.setInputValue(value);
    } else {
      this.props.onSelectionClearSelectedValueFromTextbox && this.setInputValue();
    }
  }

  handleKeyUp({ keyCode, target }){
    switch (keyCode){
      case ENTER:
        this.addItem(target.value);
        break;
      case ESCAPE:
        this.setInputValue();
        break;
      case DELETE:
        if (this.props.isChickletNone) {
          if (!target.value.length) {
            this.props.onClearChicklets();
          } else {
            this.delayedAddItem(target.value);
          }
        }
        break;
      default:
        if (this.props.isChickletNone) {
          this.delayedAddItem(target.value);
        }
        break;
    }
  }

  focus() {
    this.inputString && this.inputString.focus();
  }

  renderInput() {
    let inputClass = classNames('o-kd-select-string', 'c-kd__input',
            { 'u-input-chicklet-none': this.props.isChickletNone });
    return (
      <input
        className={inputClass}
        type="text"
        ref={ref => this.inputString = ref}
        placeholder={this.props.placeholderTextLabel}
        onKeyUp={this.handleKeyUp}
        defaultValue={this.initialInputValue()}
      />);
  }

  render() {
    return (
      <div ref={ref => this.rootElement = ref} className="c-kd-select-string">
        {this.renderInput()}
      </div>
    );
  }
};

InputString.defaultProps = defaultProps;

InputString.propTypes = propTypes;

export default InputString;