import React from 'react';
import PropTypes from 'prop-types';
import md5 from 'md5';

import IndexEntryItem from './IndexEntryItem';

const IndexEntry = ({ letter, items }) => (
  <li>
    { letter }
    <ul className="p-0 mb-2 small">
      {
        items.sort().map(indexEntryItem => <IndexEntryItem term={indexEntryItem} key={`${letter}_${md5(indexEntryItem)}`} />)
      }
    </ul>
  </li>
);

IndexEntry.propTypes = {
  letter: PropTypes.string.isRequired,
  items: PropTypes.arrayOf(PropTypes.string).isRequired,
};

const Index = ({ terms }) => {
  const termsIndex = terms.reduce((res, term) => {
    const firstLetter = term[0];
    res[firstLetter] = (res[firstLetter] || []);
    res[firstLetter].push(term);
    return res;
  }, {});

  return (
    <ul id="index" className="text-muted p-0">
      {
        Object.keys(termsIndex).sort().map(
          letter => <IndexEntry letter={letter} items={termsIndex[letter]} key={letter} />,
        )
      }
    </ul>
  );
};

Index.propTypes = {
  terms: PropTypes.arrayOf(PropTypes.string).isRequired,
};

const IndexList = ({ terms, className }) => (
  <div className={className}>
    <Index terms={terms} />
  </div>
);

IndexList.propTypes = {
  terms: PropTypes.arrayOf(PropTypes.string).isRequired,
  className: PropTypes.string.isRequired,
};

export default IndexList;
