/* eslint-disable no-return-assign */
import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import keygen from '~helpers/keygen';
import Button from '~atoms/button/button';
import Row from '~molecules/toplist/default-row';
import styles from './list.module.scss';

export default function List({
  toplist,
  hasLoadMoreButton,
  initItemsCount,
  loadItemsCount,
  pageTemplate,
  module,
  pagePath,
}) {
  const initLoadItems = Number(initItemsCount) !== 0 ? Number(initItemsCount) : 10000;
  const loadingItems = Number(loadItemsCount) !== 0 ? Number(loadItemsCount) : 10000;

  const elRefs = useRef([]);

  const loadMoreBtn = useRef(React.createRef());
  const showLoadMoreButton = hasLoadMoreButton === '1' && Number(initItemsCount) !== 0;

  function handleClick() {
    const displayed = elRefs.current.filter((item) => item.classList.contains(styles.show)).length;
    const nextItem = loadingItems + displayed;
    const lastItem =
      nextItem > elRefs.current.length ? elRefs.current.length + 1 : displayed + loadingItems;

    elRefs.current.slice(displayed, lastItem).forEach((item) => item.classList.toggle(styles.show));

    if (loadingItems + displayed > elRefs.current.length) {
      loadMoreBtn.current.classList.toggle(styles.hide);
    }
  }

  return (
    <>
      <ul className={styles.list || ''} key={keygen()}>
        {toplist.items.map((item, index) => (
          <Row
            pagePath={pagePath}
            item={item}
            tracker={toplist.tracker}
            pageTemplate={pageTemplate}
            className={index + 1 <= initLoadItems ? styles.show : null}
            key={keygen()}
            itemRefs={elRefs}
            oneliner={toplist.one_liner}
            index={index}
            module={module}
          />
        ))}
      </ul>
      {showLoadMoreButton && (
        <div ref={loadMoreBtn} className={styles.loadMore || ''}>
          <Button
            isInternalLink={false}
            btnText="Load More"
            onClick={() => handleClick()}
            buttonType="tertiary"
          />
        </div>
      )}
    </>
  );
}

List.propTypes = {
  toplist: PropTypes.shape({
    items: PropTypes.arrayOf(
      PropTypes.shape({
        name: PropTypes.string,
      })
    ),
    tracker: PropTypes.string,
    one_liner: PropTypes.string,
  }),
  hasLoadMoreButton: PropTypes.string,
  initItemsCount: PropTypes.string,
  loadItemsCount: PropTypes.string,
  pageTemplate: PropTypes.string,
  module: PropTypes.string,
  pagePath: PropTypes.string,
};
