import React, {Component} from 'react';
import PropTypes from 'prop-types';
import $ from 'jquery';
import { debounce, isUndefined } from 'lodash';

/*eslint no-console: ['error', { allow: ['warn', 'error'] }] */
export default class SplunkInput extends Component {
  constructor(props) {
    super(props);
    this.placeHolderClick = this.placeHolderClick.bind(this);
    this.handleKeyUpChange = this.handleKeyUpChange.bind(this);
    this.handleKeyUpChangeDebounced = debounce(this.handleKeyUpChange, 50);
    this.validate = this.validate.bind(this);
    this.runValidation = this.runValidation.bind(this);
    this.focus = this.focus.bind(this);
    this.blur = this.blur.bind(this);
    this.isValid = this.isValid.bind(this);
    this.state = {
      value: '',
      status: '',
      feedback: 'GOOD',
      feedbackError: 'ERROR',
      asyncValidation: props.validate ? true : false,
      placeholderCSS: {
        fontSize: '',
        top: ''
      },
      inputCSS: {
        top: ''
      },
      feedbackCSS: {
        display: 'none'
      },
      spinnerStyl: {
        display: 'none'
      },
      isValid: false
    };
  }

  static propTypes = {
    dataLocaleKey: PropTypes.string,
    title: PropTypes.string,
    tabIndex: PropTypes.number,
    inputType: PropTypes.string,
    validate: PropTypes.func,
    notifier: PropTypes.func
  };

  placeHolderClick() {
    this.input.focus();
  }

  isValid() {
    return this.state.isValid;
  }

  handleKeyUpChange() {
    //get input value and placeholder dom element
    if (this.input.val().length > 0) {
      this.setState({
        placeholderCSS: {
          fontSize: '12px',
          top: '5px'
        },
        inputCSS: {
          paddingTop: '15px'
        }
      });
    } else {
      this.setState({
        placeholderCSS: {
          fontSize: '',
          top: ''
        },
        inputCSS: {
          paddingTop: '0'
        }
      });
    }
  }

  validate(validated, feedbackString) {
    let {notifier} = this.props;

    let state = {
      status: 'error',
      isValid: false,
      spinnerStyl: {
        display: 'none'
      }
    };

    if (typeof validated == 'string') {
      this.feedback.html(validated);
      this.setState(state);
      notifier();
      return;
    }

    if (validated) {
      if (feedbackString !== undefined) {
        this.feedback.html(feedbackString);
      } else {
        this.feedback.html(this.state.feedback);
      }
      state.status = 'success';
      state.isValid = true;
    } else {
      if (feedbackString !== undefined) {
        this.feedback.html(feedbackString);
      } else {
        this.feedback.html(this.state.feedbackError);
      }
    }
    this.setState(state);
    notifier();
  }

  runValidation() {
    let value = this.input.val();
    value = value.trim();
    if (value === '') {
      this.validate('REQUIRED');
      return;
    }
    if (this.state.asyncValidation) {
      this.setState({
        spinnerStyl: {
          display: 'block'
        }
      });

      this.props.validate(value, this.validate);
    } else {
      this.validate(true);
    }
  }

  // this is called by the form builder whenever this input should receive focus
  focus() {
    this.setState({
      feedbackCSS: {
        display: 'none'
      }
    });
    this.splunkInput.addClass('focus');
  }

  blur() {
    this.splunkInput.removeClass('focus');
    this.feedback.css({ display: 'block' });
    this.runValidation();
    this.value = this.input.val();
    this.handleKeyUpChange();
  }

  render() {
    let { dataLocaleKey, title, tabIndex, inputType } = this.props;
    if (isUndefined(inputType)) {
      inputType = 'text';
    }
    return (
      <label
        className={this.state.status + ' splunk-input input-text'}
        ref={splunkInput => {
          this.splunkInput = $(splunkInput)
        }} >
        <span
          className='placeholder globalize'
          style={this.state.placeholderCSS}
          data-locale-key={dataLocaleKey}
          onClick={this.placeHolderClick} >
          {title}
        </span>
        <span
          className='feedback'
          style={this.state.feedbackCSS}
          ref={feedback => {
            this.feedback = $(feedback)
          }} />
        <span
          className='glyphicon glyphicon-refresh gly-spin input-spinner'
          style={this.state.spinnerStyl} />
        <div className='input-wrap'>
          <input
            type={inputType}
            name='username'
            tabIndex={tabIndex}
            className='exlane-fields'
            style={this.state.inputCSS}
            ref={input => {
              this.input = $(input)
            }}
            onChange={this.handleKeyUpChangeDebounced}
            onKeyUp={this.handleKeyUpChangeDebounced}
            onFocus={this.focus}
            onBlur={this.blur} />
        </div>
      </label>
    );
  }
}