import React from 'react';
import classnames from 'classnames';
import ReactDOM from 'react-dom';
import { calculateTextWidth } from 'utils/html';
import {
  switchWorkspace,
  addWorkspace,
  removeWorkspace,
  changeWorkspaceName
} from 'actions/workspaces';

class WorkspaceNav extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showMenu: false,
      workspaceName: props.workspaces.getIn([props.activeWorkspaceIndex, 'name']),
      editingWsName: false
    };
  }

  componentWillReceiveProps(nextProps) {
    const activeName = nextProps.workspaces.getIn([nextProps.activeWorkspaceIndex, 'name']);
    if (activeName !== this.state.workspaceName) {
      this.setState({workspaceName: activeName});
    }
    if (this.state.editingWsName && nextProps.activeWorkspaceIndex !== this.props.activeWorkspaceIndex) {
      this.setState({editingWsName: false});
    }
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.editingWsName && !prevState.editingWsName) {
      this.refs.wsNameInput.focus();
    }
  }

  setInputWidth() {
    const input = this.refs.wsNameInput;
    return input ? calculateTextWidth(input.value, input) : 'auto';
  }

  handleRemoveWorkspace(e, index) {
    e.stopPropagation();
    removeWorkspace(index);
  }

  handleWstabKeyDown(e) {
    const key = e.which || e.keyCode || 0;
    switch (key) {
    case 13:
      return this.saveName();
    case 27:
      return this.toggleEditWorkspaceName();
    default:
      return false;
    }
  }

  changeWorkspaceName(newName) {
    this.setState({workspaceName: newName});
  }

  saveName() {
    const { workspaceName } = this.state;
    if (workspaceName.trim().length) {
      changeWorkspaceName(workspaceName);
      this.setState({editingWsName: false});
    }
  }

  toggleEditWorkspaceName(e) {
    this.setState({editingWsName: !this.state.editingWsName});
  }

  render() {
    const { workspaces, activeWorkspaceIndex } = this.props;
    const { editingWsName } = this.state;

    let workspaceList = workspaces.map((workspace, i) => {
      const tabIsActive = i === activeWorkspaceIndex;
      const workspaceClass = tabIsActive ? 'ws-tabs__tab ws-tabs__tab--active' : 'ws-tabs__tab';
      const workspaceName = workspace.get('name');
      return (
        <li key={i} className={workspaceClass} onClick={(e) => switchWorkspace(i, e)} onDoubleClick={(e) => this.toggleEditWorkspaceName(e)}>
          {
            tabIsActive && editingWsName
            ?
            (<input
              type="text"
              ref="wsNameInput"
              style={{width: this.setInputWidth()}}
              defaultValue={workspaceName}
              onKeyDown={(e) => this.handleWstabKeyDown(e)}
              onChange={(e) => this.changeWorkspaceName(e.target.value)}
            />)
            :
            workspaceName
          }
          {(workspaces.size > 1 ) ? (
            <button className="ws-tabs__tab-close" onClick={(e) => this.handleRemoveWorkspace(e, i)}>
              <i className="bzpro-icon-close"></i>
            </button>
          ) : null}
        </li>
      );
    });
    workspaceList = workspaceList.push(
      <li key="999" className="ws-tabs__tab" onClick={() => addWorkspace()}>+ Add</li>
    );
    return (
      <section className="WorkspaceNav">
        <ul className="ws-tabs">
          {workspaceList}
        </ul>
      </section>
    );
  }
}

WorkspaceNav.propTypes = {
  workspaces: React.PropTypes.object,
  activeWorkspaceIndex: React.PropTypes.number
};

export default WorkspaceNav;
