import React, { Component, PropTypes } from 'react';
import { TextField } from 'material-ui';
import Spacing from 'material-ui/styles/spacing';
import { yellow800, grey100, green200, red200 } from 'material-ui/styles/colors';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import UCdefaultTheme from '../../themes/DefaultTheme';

import './InputField.css';

export default class InputField extends Component {

  constructor(props) {
    super(props);

    this.state = {
      inputLength: 0,
      inputColor: grey100,
      value: '',
    };

    this.getValue = this.getValue.bind(this);
    this.setValue = this.setValue.bind(this);

    this.onChange = this.onChange.bind(this);
    this.onFocus = this.onFocus.bind(this);
    this.onBlur = this.onBlur.bind(this);
  }

  getChildContext() {
    const theme = getMuiTheme(UCdefaultTheme);

    theme.appBar.textColor = 'black';
    theme.appBar.spacing = Spacing.desktopSubheaderHeight;
    theme.flatButton.secondaryColor = yellow800;
    theme.flatButton.primaryColor = '#e00122';

    return {
      muiTheme: theme,
    };
  }

  componentDidMount() {
    if (this.textField) {
      this.textField.focus();
    }
  }

  getValue() {
    return this.state.value;
  }

  setValue(val) {
    this.setState({
      value: val,
      inputLength: val.length,
    });
  }

  onFocus() {
    this.setState({
      inputColor: this.state.inputLength === this.props.maxLength ? green200 : red200,
    });
  }

  onBlur() {
    this.setState({ inputColor: grey100 });
  }

  onChange(event) {
    this.props.onChange(event);

    let newValue = event.target.value;
    let newLength = event.target.value.length;

    if (newLength > this.props.maxLength) {
      newLength = this.props.maxLength;
      newValue = event.target.value.substring(0, this.props.maxLength);
    }

    this.setState({
      value: newValue,
      inputLength: newLength,
      inputColor: newLength === this.props.maxLength ? green200 : red200,
    });
  }

  render() {
    return (
      <div className="ih-input-group">
        <TextField
          ref={(c) => { this.textField = c; }}
          value={this.state.value}
          className="ih-input"
          hintText={this.props.hintText}
          onChange={this.onChange}
          onFocus={this.onFocus}
          onBlur={this.onBlur}
          underlineFocusStyle={{ borderColor: this.state.inputColor }}
          fullWidth
        />
        <span style={{ color: this.state.inputColor }} className="ih-input-count">
          {this.state.inputLength}/{this.props.maxLength}
        </span>
      </div>
    );
  }
}

InputField.propTypes = {
  hintText: PropTypes.string,
  maxLength: PropTypes.number,
  onChange: PropTypes.func,
  focus: PropTypes.bool,
};

InputField.childContextTypes = {
  muiTheme: PropTypes.object,
};
