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

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

import { CATEGORY_TYPE, RULE_TYPE } from '../../constants.js';
import LoadingIndicator from '../../../../components/LoadingIndicator.js';
import CategoryItem from './CategoryItem.js';
import SavedItem from './SavedItem.js';
import ReadButton from './ReadButton.js';

// TODO: show empty category message
class Sidebar 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 (
      <div className="sidebar">
        {(this.props.categories.isFetching || this.props.rules.isFetching) && (
          <LoadingIndicator />
        )}

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

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

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)(Sidebar);
