import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormattedRelative } from 'react-intl';
import ReactMarkdown from 'react-markdown';

import Tag from './Tag';
import AnnotationQuote from './AnnotationQuote';

export default class Annotation extends Component {
  user() {
    const { annotation } = this.props;

    const [userName, instanceName] = annotation.user.replace('acct:', '').split('@');

    return (
      <strong>
        { userName }
        <span className="text-muted">{`@${instanceName}`}</span>
      </strong>
    );
  }

  tags() {
    const { annotation, metacategories, categories } = this.props;

    const tagMetacategories = [];
    const others = [];

    annotation.tags.forEach((tagStr) => {
      if (tagStr.startsWith('cat:')) {
        tagMetacategories.push(tagStr);
      } else {
        others.push(tagStr);
      }
    });

    /* eslint-disable max-len */
    return (
      <div className="tags">
        { tagMetacategories.map(tag => <Tag tag={tag} metacategories={metacategories} categories={categories} />) }
        { others.map(tag => <Tag tag={tag} metacategories={metacategories} categories={categories} />) }
      </div>
    );
    /* eslint-enable max-len */
  }

  render() {
    const { annotation, metacategories } = this.props;

    const dateUpdated = (
      <FormattedRelative
        value={annotation.updated}
      />
    );

    let body = '';

    if (annotation.text || annotation.text !== '') {
      body = (
        <div className="comment-body text-muted font-italic">
          <ReactMarkdown source={(annotation.text)} />
        </div>
      );
    }

    return (
      <div className="card">
        <div className="card-header">
          <a href={annotation.uri}>{ annotation.document.title }</a>
        </div>
        <ul className="list-group list-group-flush small">
          <li className="highlight list-group-item d-block">
            <AnnotationQuote annotation={annotation} metacategories={metacategories} />
            <div className="comment-info">
              { `${this.user()} - ${dateUpdated} `}
              <a href={annotation.links.incontext}>#</a>
            </div>
            { body }
            { this.tags() }
          </li>
        </ul>
      </div>
    );
  }
}

Annotation.propTypes = {
  annotation: PropTypes.isRequired,
  metacategories: PropTypes.isRequired,
  categories: PropTypes.isRequired,
};
