import $ from 'jquery';
import React from 'react';
import classnames from 'classnames';
import ReactTabGroupButton from './react-tab-group-button.jsx';
import ReactTabGroupSection from './react-tab-group-section.jsx';

class ReactTabGroup extends React.Component {

  static defaultProps = {
    active: 0,
    buttons: ['button-1', 'button-2', 'button-3'],
    sections: ['section-1', 'section-2', 'section-3'],
    onSwitch: null
  }

  static propTypes = {
    active: React.PropTypes.number,
    buttons: React.PropTypes.array,
    sections: React.PropTypes.array,
    onSwitch: React.PropTypes.func
  }

  displayName = 'ReactTabGroup';

  constructor(props) {
    super(props);
    this.state = {
      active: props.active
    };
  }

  // Click handle.
  handleClick(index) {
    const newState = { active: index };
    const {onSwitch} = this.props;

    if ( $.isFunction(onSwitch) ) {
      onSwitch( newState.active );
    }

    // Update state.
    this.setState(newState);
  }

  render() {
    return (
      <div className={ classnames('tabbar-group', this.props.className) }>
        <div className="tabbar-header row no-gutter">
          { // Tabbar buttons.
            this.props.buttons.map((button, index) => {
              return $.type(button) === 'string' ? <ReactTabGroupButton key={index} content={button} className={ classnames({active: this.state.active === index}) } onClick={ this.handleClick.bind(this, index) } /> : button
            })
          }
        </div>
        <div className="tabbar-section">
          { // Tabbar sections.
            this.props.sections.map((section, index) => {
              let active = this.state.active === index;
              return <ReactTabGroupSection key={index} content={active ? section : ''} className={ classnames({active: active}) } />
            })
          }
        </div>
      </div>
    );
  }
}

export default ReactTabGroup;
