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

// Style
let classes = {};
/* istanbul ignore next */
if (typeof window !== 'undefined' || typeof _COMPILED_ === 'undefined') classes = require('./style.module.scss');

class SearchTabs extends React.Component {
  constructor(props) {
    super(props);
    this.handleTabChange = this.handleTabChange.bind(this);
  }

  handleTabChange(e, tab) {
    e.persist();
    // if not spacebar or enter
    if (e.type === 'keydown' && e.keyCode !== 32 && e.keyCode !== 13) return null;
    return this.props.onTabChange(tab);
  }

  render() {
    const { activeTab, tabNames, tabFilters } = this.props;

    const tabs = [
      { moduleName: '', label: 'All', icon: <i className="icon icon-search" /> },
      { moduleName: 'docs', label: 'Guides', icon: <i className="icon icon-documentation-2" /> },
      { moduleName: 'tutorials', label: 'Recipes', icon: <i className="icon icon-recipes" /> },
      { moduleName: 'reference', label: 'Reference', icon: <i className="icon icon-reference-2" /> },
      { moduleName: 'changelog', label: 'Changelog', icon: <i className="icon icon-changelog-2" /> },
      { moduleName: 'discuss', label: 'Discussions', icon: <i className="icon icon-discussions-2" /> },
      { moduleName: 'custompages', label: 'Pages', icon: <i className="icon icon-custom-pages" /> },
    ].filter(tab => {
      const { moduleName } = tab;
      if (moduleName === '') return true;
      return tabFilters.includes(moduleName);
    });

    return (
      <div className={classes.SearchTabs}>
        <div className="Tabs Tabs-list">
          {tabs.map(tab => {
            let activeClass = '';
            if (activeTab === tab.label) activeClass = 'Tabs-listItem_active';
            return (
              <div
                key={tab.label}
                className={[classes['SearchTabs-Tab'], 'Tabs-listItem', activeClass].join(' ')}
                onClick={e => this.handleTabChange(e, tab.label)}
                onKeyDown={e => this.handleTabChange(e, tab.label)}
                role="button"
                tabIndex={-1}
              >
                <span className={classes['SearchTabs-Tab']}>
                  {tab.icon}
                  {(tabNames && tab.moduleName && tab.moduleName in tabNames && tabNames[tab.moduleName]) || tab.label}
                </span>
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}

SearchTabs.propTypes = {
  activeTab: PropTypes.string,
  onKeyDown: PropTypes.func,
  onTabChange: PropTypes.func,
  tabFilters: PropTypes.array,
  tabNames: PropTypes.object,
};

export default SearchTabs;
