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

import { CATEGORY_TYPE } from '../../constants.js';
import { selectCategory, fetchCategory } from '../../actions/categories.js';
import { fetchPostsBySection } from '../../actions/posts.js';

import { isSelected } from './functions.js';
import RuleItem from './RuleItem.js';

class CategoryItem extends React.Component {
  state = { open: false };

  toggleRules() {
    this.setState({ open: !this.state.open });
  }

  handleSelect() {
    const category = this.props.category;

    this.props.selectCategory(category);
    this.props.fetchPostsBySection({ ...category, type: CATEGORY_TYPE });
    this.props.fetchCategory(category);
  }

  render() {
    const chevronClass = this.state.open ? 'fas fa-chevron-down' : 'fas fa-chevron-right';
    const selected = isSelected(this.props.category, this.props.selected, CATEGORY_TYPE);
    const className = selected
      ? 'sidebar__container sidebar__container--selected'
      : 'sidebar__container';

    const ruleItems = this.props.rules.map(rule => {
      return <RuleItem key={rule.id} rule={rule} selected={this.props.selected} />;
    });

    return (
      <li className="sidebar__item">
        <div className={className}>
          <span className="sidebar__icon" onClick={() => this.toggleRules()}>
            <i className={chevronClass} />
          </span>

          <div className="sidebar__text" onClick={() => this.handleSelect()}>
            <span>{this.props.category.name}</span>
            <span className="badge">{this.props.category.unread}</span>
          </div>
        </div>

        {ruleItems.length > 0 && this.state.open && (
          <ul className="rules">{ruleItems}</ul>
        )}
      </li>
    );
  }
}

const mapDispatchToProps = dispatch => ({
  selectCategory: category => dispatch(selectCategory(category)),
  fetchPostsBySection: section => dispatch(fetchPostsBySection(section)),
  fetchCategory: category => dispatch(fetchCategory(category)),
});

export default connect(null, mapDispatchToProps)(CategoryItem);
