import React from 'react';
import PropTypes from 'prop-types';
import { NavLink } from 'react-router-dom';
import { FormattedMessage, injectIntl, intlShape } from 'react-intl';
import md5 from 'md5';

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

import './TermEntry.scss';


function getTermDefinition(annotation) {
  if (annotation.text) {
    return annotation.text;
  }

  let selector;

  if (annotation.target[0].selector) {
    selector = annotation.target[0].selector.find(s => s.type === 'TextQuoteSelector');
  }

  if (selector) {
    return selector.exact;
  }
  return '';
}

const TermEntry = ({ term, termDef, intl }) => {
  const key = `${md5(term)}-term-entry`;

  let firstDefinition = '';

  if (termDef.definitions.length > 0) {
    firstDefinition = getTermDefinition(termDef.definitions[0]);
  }
  if (!firstDefinition) {
    firstDefinition = <span className="text-muted font-italic"><FormattedMessage id="ui.termEntry.noDefinition" defaultMessage="No definition yet" /></span>;
  }

  const definitionsTitle = intl.formatMessage({ id: 'ui.termEntry.nbDefinitions', defaultMessage: 'Nb. definitions' });
  const referencesTitle = intl.formatMessage({ id: 'ui.termEntry.nbReferences', defaultMessage: 'Nb. references' });
  const commentsTitle = intl.formatMessage({ id: 'ui.termEntry.nbComments', defaultMessage: 'Nb. comments' });

  return (
    <tr id={key}>
      <th scope="row" className="term-entry-term"><NavLink to={`/term/${encodeURIComponent(term)}`} className="term-entry-term-link">{term}</NavLink></th>
      <td className="term-entry-def">
        <p>{firstDefinition}</p>
        <p className="glossary-table-counts align-text-bottom text-right text-muted small">
          <span title={definitionsTitle}>
            <NavLink to={`/term/${encodeURIComponent(term)}`} className="term-entry-term-link">
              <FontAwesomeIcon icon="file-alt" />
              {' '}
              <span>{ termDef.definitions.length }</span>
            </NavLink>
          </span>
          <span title={referencesTitle}>
            <NavLink to={`/term/${encodeURIComponent(term)}/1`} className="term-entry-term-link">
              <FontAwesomeIcon icon="share-alt" />
              {' '}
              <span>{ termDef.references.length }</span>
            </NavLink>
          </span>
          <span title={commentsTitle}>
            <NavLink to={`/term/${encodeURIComponent(term)}/2`} className="term-entry-term-link">
              <FontAwesomeIcon icon="comments" />
              {' '}
              <span>{ termDef.messagesCount || 0 }</span>
            </NavLink>
          </span>
        </p>
      </td>
    </tr>
  );
};

TermEntry.propTypes = {
  term: PropTypes.string.isRequired,
  termDef: PropTypes.object.isRequired,
  intl: intlShape.isRequired,
};

export default injectIntl(TermEntry);
