import React from 'react';

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

import { fetchCategories } from './actions/categories';
import { filterPosts } from './components/postlist/filters.js';

import ScrollTop from './components/ScrollTop.js';
import HomepageSidebar from './components/sidebar/Sidebar.js';
import PostList from './components/postlist/PostList.js';
import PostModal from './components/PostModal.js';
import Messages from '../../components/Messages.js';

class App extends React.Component {
  state = { postListNode: null };

  constructor(props) {
    super(props);

    this.postListRef = node => {
      this.setState({ postListNode: node });
    };
  }

  componentDidMount() {
    this.props.fetchCategories();
  }

  render() {
    return (
      <>
        <HomepageSidebar navLinks={this.props.navLinks} />
        <PostList
          feedUrl={this.props.feedUrl}
          timezone={this.props.timezone}
          forwardedRef={this.postListRef}
          postsByType={this.props.postsByType}
        />

        {!isEqual(this.props.post, {}) && (
          <PostModal
            post={this.props.post}
            rule={this.props.rule}
            category={this.props.category}
            selectedType={this.props.selectedType}
            feedUrl={this.props.feedUrl}
            categoriesUrl={this.props.categoriesUrl}
            timezone={this.props.timezone}
            autoMarking={this.props.autoMarking}
          />
        )}

        <ScrollTop postListNode={this.state.postListNode} />

        {this.props.error && (
          <Messages messages={[{ type: 'error', text: this.props.error.message }]} />
        )}
      </>
    );
  }
}

const mapStateToProps = state => {
  const { error } = state.error;
  const postsByType = filterPosts(state);

  if (!isEqual(state.selected.post, {})) {
    const ruleId = state.selected.post.rule.id;

    const rule = state.rules.items[ruleId];
    const category = state.categories.items[rule.category];

    return {
      category,
      error,
      rule,
      post: state.selected.post,
      selectedType: state.selected.item.type,
      postsByType: postsByType,
    };
  }

  return { error, post: state.selected.post, postsByType: postsByType };
};

const mapDispatchToProps = dispatch => ({
  fetchCategories: () => dispatch(fetchCategories()),
});

export default connect(mapStateToProps, mapDispatchToProps)(App);
