import React from 'react';
import { connect } from 'react-redux';
import Cookies from 'js-cookie';

import { CATEGORY_TYPE, SAVED_TYPE } from '../../constants.js';
import { selectPost, toggleSaved } from '../../actions/posts.js';
import { formatDatetime } from '../../../../utils.js';

class PostItem extends React.Component {
  render() {
    const rule = { ...this.props.post.rule };
    const post = { ...this.props.post };
    const token = Cookies.get('csrftoken');
    const publicationDate = formatDatetime(post.publicationDate);

    const titleClassName = post.read
      ? 'posts__header posts__header--read'
      : 'posts__header';
    const savedIconClass = post.saved ? 'saved-icon saved-icon--saved' : 'saved-icon';

    const ruleUrl = `${this.props.feedUrl}/${rule.id}/`;

    return (
      <li className="posts__item" ref={this.props.forwardedRef}>
        <h5
          className={titleClassName}
          title={post.title}
          onClick={() => this.props.selectPost(post)}
        >
          {post.title}
        </h5>

        <div className="posts-info">
          <span className="posts-info__date" title={publicationDate}>
            {publicationDate} {post.author && `By ${post.author}`}
          </span>
          {[CATEGORY_TYPE, SAVED_TYPE].includes(this.props.selected.type) && (
            <span className="badge">
              <a href={ruleUrl} target="_blank" rel="noopener noreferrer">
                {rule.name}
              </a>
            </span>
          )}
          <a
            className="posts-info__link"
            href={post.url}
            target="_blank"
            rel="noopener noreferrer"
          >
            <i className="fas fa-external-link-alt"></i>
          </a>
          <span
            className={savedIconClass}
            onClick={() => this.props.toggleSaved(post, token)}
          />
        </div>
      </li>
    );
  }
}

const mapDispatchToProps = dispatch => ({
  selectPost: post => dispatch(selectPost(post)),
  toggleSaved: (post, token) => dispatch(toggleSaved(post, token)),
});

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