import $ from 'jquery';
import React from 'react';
import classnames from 'classnames';
import TabbarButton from './react-tabbar-button.jsx';
import TabbarSection from './react-tabbar-section.jsx';

class ReactTabbar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      active: props.default
    };
    this.displayName = 'ReactTabbar';
  }

  // 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' ? <TabbarButton 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 <TabbarSection key={index} content={active ? section : {}} className={ classnames({active: active}) } />
            })
          }
        </div>
      </div>
    );
  }
}

// Set default properties.
ReactTabbar.defaultProps = {
  default: 0,
  buttons: ['button-1', 'button-2', 'button-3'],
  sections: ['section-1', 'section-2', 'section-3'],
  onSwitch: null
};

// Set default propTypes.
ReactTabbar.propTypes = {
  default: React.PropTypes.number,
  buttons: React.PropTypes.array,
  sections: React.PropTypes.array,
  onSwitch: React.PropTypes.func
};

export default ReactTabbar;
