/* eslint-disable react/forbid-prop-types */
import PropTypes from 'prop-types';
import classnames from 'classnames';
import groupBy from 'lodash/groupBy';
import useDateFormat from "../../../hooks/useDateFormat/index.js";
import customizable from "../../../utils/css/customizable.js";
import CommaAnd from "../CommaAnd/index.js";
import Name from './Name';
import classes from './styles.module.scss';

/**
 * Render a standard POLITICO byline.
 */
const Byline = function Byline(props) {
  const {
    authors,
    published,
    updated,
    nameAs: NameTag,
    separator,
    dateFormat
  } = props;
  const publishedFormat = useDateFormat(published, {
    format: dateFormat
  });
  const publishedISO = useDateFormat(published, {
    format: 'iso'
  });
  const updatedFormat = useDateFormat(updated, {
    format: dateFormat
  });
  const updatedISO = useDateFormat(updated, {
    format: 'iso'
  });
  const bylines = groupBy(authors, d => d.by || 'By');
  return <div className={classnames(customizable('Byline'), classes.container)}>
      <div>
        {Object.entries(bylines).map(([by, names]) => <div key={by} className={classnames(customizable('Byline__group'), classes.byline)}>
            {by}
            {' '}
            <CommaAnd items={names.map(name => <NameTag name={name} />)} />
          </div>)}
      </div>

      {published && <span className={classnames(customizable('Byline__published'))}>
          <time className={classnames(classes.timestamp)} dateTime={publishedISO}>
            {publishedFormat}
          </time>
        </span>}

      {published && updated && <>
          {' '}
          {separator}
          {' '}
        </>}

      {updated && <span className={classnames(customizable('Byline__updated'))}>
          Updated
          {' '}
          <time className={classnames(classes.timestamp)} dateTime={updatedISO}>
            {updatedFormat}
          </time>
        </span>}
    </div>;
};
Byline.defaultProps = {
  published: undefined,
  updated: undefined,
  nameAs: Name,
  dateFormat: 'politico',
  separator: '|'
};
Byline.propTypes = {
  authors: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.shape({
    name: PropTypes.string,
    by: PropTypes.string,
    tagline: PropTypes.string
  }), PropTypes.any])).isRequired,
  published: PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(Date)]),
  updated: PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(Date)]),
  dateFormat: PropTypes.string,
  separator: PropTypes.node,
  nameAs: PropTypes.elementType
};
export default Byline;