import React from 'react';
import PropTypes from 'prop-types';

import Tab from './Tab';

// Style
/* istanbul ignore next */
if (typeof window !== 'undefined') require('./style.scss');

class Tabs extends React.Component {
  static propTypes = {
    children: PropTypes.instanceOf(Array).isRequired,
    className: PropTypes.shape({
      root: PropTypes.string,
      tabs: PropTypes.string,
    }),
  };

  constructor(props) {
    super(props);
    this.state = {
      activeTab: this.props.children[0].props.label,
    };
  }

  activate = tab => {
    this.setState({ activeTab: tab });
  };

  render() {
    const {
      activate,
      props: { children, className = { root: '', tabs: '' } },
      state: { activeTab },
    } = this;

    return (
      <div className={`Tabs ${className.root || ''}`}>
        <ol className={`Tabs-list ${className.tabs || ''}`}>
          {children.map(child => {
            const { label } = child.props;
            let key = label;
            /* use children as key for labels with markup */
            if (typeof label === 'object' && label !== null) key = label.props.children;
            return <Tab key={key} activeTab={activeTab} className="Tabs-listItem" label={label} onClick={activate} />;
          })}
        </ol>
        {children.map(child => child.props.label === activeTab && child.props.children)}
      </div>
    );
  }
}

export default Tabs;
