import React from 'react';
import classNames from 'classnames';

import '../base';
import style from './Toolbar.Search.styl';

import { visualProvided } from '../atoms/VisualProvider';
import Textfield from '../atoms/Textfield';
import IconButton from '../atoms/IconButton';
import Icon from '../atoms/Icon';

class ToolbarSearch extends React.Component {

  constructor(props) {
    super(props);
    const active = !!(props.value || props.defaultValue);
    const open = props.open || active || false;
    this.state = { open, active };

    this.open = this.open.bind(this);
    this.close = this.close.bind(this);
    this.closeIfInactive = this.closeIfInactive.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.onKeyDown = this.onKeyDown.bind(this);
  }

  componentDidUpdate(prevProps, prevState) {
    const newState = this.state;
    if (!prevState.open && newState.open && this.textFieldComponent) {
      this.textFieldComponent.focus();
    }
  }

  onKeyDown(e) {
    const ESC = 27;
    if (e.keyCode !== ESC) return;
    const input = e.target;
    input.value = '';
    this.close();
    this.handleChange(e);
  }

  open() {
    this.setState({ open: true });
  }

  close() {
    this.setState({ open: false });
  }

  closeIfInactive() {
    if (!this.state.active) {
      this.close();
    }
  }

  handleChange(e) {
    this.setState({ active: !!e.target.value });

    const { onChange, onBeforeChange, onAfterChange } = this.props;
    if (onBeforeChange) onBeforeChange(e);
    if (onChange) onChange(e);
    if (onAfterChange) onAfterChange(e);
  }

  render() {
    const { t, placeholder = t('toolbarSearchPlaceholder'), value, defaultValue } = this.props;
    const { open, active } = this.state;

    const containerClass = classNames({
      [style.search]: true,
      [style.open]: open
    });

    const inputClass = classNames({
      [style.input]: true,
      [style.open]: open
    });

    const buttonClass = classNames({
      [style.button]: true,
      [style.open]: open
    });

    return (
      <div
        className={containerClass}
        ref={(ref) => { this.containerNode = ref; }}
        style={{ left: 0 }}
      >
        <IconButton
          onClick={this.open}
          className={buttonClass}
          icon="doka-icon-search"
          active={active}
        >
          {t('toolbarSearchToggleLabel')}
        </IconButton>
        <div className={inputClass} style={{ width: open ? '100%' : '0%' }}>
          <Textfield
            ref={(ref) => { this.textFieldComponent = ref; }}
            onBlur={this.closeIfInactive}
            onChange={this.handleChange}
            onKeyDown={this.onKeyDown}
            {...{ placeholder, value, defaultValue }}
          />
          <Icon onClick={this.close} info name="doka-icon-search" />
        </div>
      </div>
    );
  }
}

export default visualProvided(ToolbarSearch);
