import React from 'react';
import { connect } from 'react-redux';

import Sidebar from '../../../../components/Sidebar.js';
import LoadingIndicator from '../../../../components/LoadingIndicator.js';
import { CATEGORY_TYPE, RULE_TYPE } from '../../constants.js';

import CategoryItem from './CategoryItem.js';
import SavedItem from './SavedItem.js';
import ReadButton from './ReadButton.js';

import { filterCategories, filterRules } from './filters.js';

class HomepageSidebar extends React.Component {
  render() {
    const categoryItems = this.props.categories.items.map(category => {
      const rules = this.props.rules.items.filter(rule => {
        return rule.category === category.id;
      });

      return (
        <CategoryItem
          key={category.id}
          category={category}
          rules={rules}
          selected={this.props.selected.item}
        />
      );
    });

    const showReadButton =
      this.props.selected.item &&
      [CATEGORY_TYPE, RULE_TYPE].includes(this.props.selected.item.type);

    return (
      <Sidebar navLinks={this.props.navLinks} includeBorder={true}>
        {(this.props.categories.isFetching || this.props.rules.isFetching) && (
          <LoadingIndicator />
        )}

        <ul className="sidebar__list">
          <SavedItem selected={this.props.selected.item} />
          {categoryItems}
        </ul>

        {showReadButton && <ReadButton />}
      </Sidebar>
    );
  }
}

const mapStateToProps = state => ({
  categories: { ...state.categories, items: filterCategories(state.categories.items) },
  rules: { ...state.rules, items: filterRules(state.rules.items) },
  selected: state.selected,
});

export default connect(mapStateToProps)(HomepageSidebar);
