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

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

import './DocumentAnnotation.scss';

const User = ({ annotation }) => {
  const [userName, instanceName] = annotation.user.replace('acct:', '').split('@');
  return (
    <strong>
      { userName }
      <span className="text-muted">{`@${instanceName}`}</span>
    </strong>
  );
};

User.propTypes = {
  annotation: PropTypes.object.isRequired,
};

const TagList = ({ annotation, metacategories, categories }) => annotation.tags.map(
  tag => <Tag tag={tag} metacategories={metacategories} categories={categories} key={`${annotation.uri}_${tag}`} />,
);

TagList.propTypes = {
  annotation: PropTypes.object.isRequired,
  metacategories: PropTypes.arrayOf(PropTypes.object).isRequired,
  categories: PropTypes.arrayOf(PropTypes.string).isRequired,
};


const DocumentAnnotation = ({ annotation, metacategories, categories }) => (
  <li className="highlight list-group-item d-block">

    <AnnotationQuote annotation={annotation} metacategories={metacategories} />

    <div className="comment-info">
      <User annotation={annotation} />
      {' - '}
      <FormattedRelative value={annotation.updated} />
      {' '}
      <a href={annotation.links.incontext} target="_blank" rel="noopener noreferrer">#</a>
    </div>

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

    <div className="tags">
      <TagList annotation={annotation} metacategories={metacategories} categories={categories} />
    </div>
  </li>
);

DocumentAnnotation.propTypes = {
  annotation: PropTypes.object.isRequired,
  metacategories: PropTypes.arrayOf(PropTypes.object).isRequired,
  categories: PropTypes.arrayOf(PropTypes.string).isRequired,
};

export default DocumentAnnotation;
