import React, { Component } from 'react';
import { connect } from 'react-redux';
import { saveQuestion } from '../../../actions/questionActions';
import Validation from '../../../utils/validation/Validation';
import InputValidation from '../../../utils/validation/InputValidation';
import { TooltipTrigger } from 'pui-react-tooltip'

@connect(store => ({}))
class Textfield extends Component {
  constructor(props) {
    super(props);
    this.state = {
      answer: this.props.question.answer ? this.props.question.answer : '',
      hasError: false,
    };

    this.setErrorState = this.setErrorState.bind(this);
  }

  setErrorState(errorObject) {
    this.setState(errorObject);
  }

  componentWillMount() {
    this.props.bubbleToQuestion(this.props.question.answer);
  }

  change(event) {
    this.setState({ answer: event.target.value }, () => {
      this.props.bubbleToQuestion(this.state.answer);
    });
  }

  render() {
    return (
      <div className="questionContainer">
        <div className="questionRow">
          <span>
            {this.props.question.text}
            {this.props.question.tip_text ?
              <TooltipTrigger tooltip={this.props.question.tip_text}>
                <i className="fa fa-info-circle" aria-hidden="true" />
              </TooltipTrigger>
              : ''}
          </span>
          <input
            type="text"
            onChange={event => this.change(event)}
            disabled={this.props.isDisabled}
            onBlur={this.props.dispatch.bind(
              this,
              saveQuestion(
                this.props.year,
                this.props.question,
                this.state.answer,
                this.props.questionPlusId,
                this.state.hasError,
              ),
            )}
            value={this.state.answer}
            className={"textInput " + (this.props.year ? (this.props.question.hasError ? 'errorInput' : '') : (this.state.hasError ? 'errorInput' : ''))}
          />
        </div>

        <div className={this.props.year ? (this.props.question.hasError ? 'questionRow errorMessage' : 'hide') : (this.state.hasError ? 'questionRow errorMessage' : 'hide')}>        
          {this.props.year ? (<Validation
            validationType={this.props.question.validation_type}
            answer={this.state.answer}
            question={this.props.question}
            questionPlusId={this.props.questionPlusId}
          />) : (<InputValidation
            input={this.state.answer}
            validationType={this.props.question.validation_type}
            setErrorState={this.setErrorState} />)}
        </div>

        <div className={this.props.question.feedback !== "" ? 'questionRow warmingMessage' : 'hide'}>
          {this.props.question.feedback}
        </div>
      </div>
    );
  }
}

export default Textfield;
