/* eslint-disable react/jsx-no-bind */
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable react/prop-types */
import React, { useRef, useState, useCallback, startTransition } from 'react';
import PropTypes from 'prop-types';

import useTranslate from '~hooks/useTranslate/useTranslate';
import Button from '~atoms/button/button';
import Row from '../../../../../components/molecules/toplist/row/variant-one';
import VerifiedAuthor from '../../../../../images/icons/verified-author';
import styles from './list.module.scss';
import styleTemplateOne from './template-one.module.scss';
import styleTemplateTwo from './template-two.module.scss';
import styleTemplateThree from './template-three.module.scss';

export default function List({
  pagePath,
  toplist,
  moduleName,
  hasLoadMoreButton,
  initItemsCount,
  loadItemsCount,
  pageTemplate,
  modulestyle,
  removeInactiveItems = true,
  template,
  loadMoreIcon = null,
  modulePosition,
  verifyIcon = <VerifiedAuthor />,
}) {
  const initLoadItems = Number(initItemsCount) !== 0 ? Number(initItemsCount) : 10000;
  const loadingItems = Number(loadItemsCount) !== 0 ? Number(loadItemsCount) : 10000;

  const isPPCPage = pageTemplate && pageTemplate.toLowerCase() === 'ppc';

  const elRefs = useRef([]);
  let { items } = toplist;

  if (removeInactiveItems) {
    items = items && items.filter((res) => res.status === 'active');
  }

  if ((!hasLoadMoreButton || parseInt(hasLoadMoreButton) === 0) && parseInt(initItemsCount) > 0) {
    items = items && items.splice(0, initItemsCount);
  }
  
  const [visibleCount, setVisibleCount] = useState(initLoadItems);

  const showLoadMoreButton =
    hasLoadMoreButton === '1' && Number(initItemsCount) < toplist.items?.length;

  const allItemsVisible = items && visibleCount >= items.length;

  const handleClick = useCallback(() => {
    startTransition(() => {
      setVisibleCount((prev) => {
        const next = prev + loadingItems;
        return items && next >= items.length ? items.length : next;
      });
    });
  }, [loadingItems, items]);

  const templateStyle = () => {
    switch (modulestyle) {
      case 'template_two':
        return styleTemplateTwo.templateTwo;
      case 'template_three':
        return styleTemplateThree.templateThree;
      default:
        return styleTemplateOne.templateOne;
    }
  };

  const isGrid = modulestyle === 'template_two';

  return (
    <>
      <ol className={`${styles.list || ''} ${templateStyle()} `}>
        {items && items.map((item, index) => (
          <Row
            pagePath={pagePath}
            item={item}
            moduleName={moduleName}
            tracker={toplist.tracker}
            oneliner={toplist.one_liner}
            isPPC={isPPCPage}
            index={index}
            className={index < visibleCount ? styles.show : null}
            key={item.id || item.name || index}
            itemRefs={elRefs}
            template={template}
            layout={isGrid ? 'grid' : 'list'}
            verifyIcon={verifyIcon}
            showAuthor={modulestyle !== 'template_three'}
            itemPosition={index + 1}
            modulePosition={modulePosition}
          />
        ))}
      </ol>
      {showLoadMoreButton && !allItemsVisible && (
        <div className={styles.loadMore}>
          <Button
            isInternalLink={false}
            btnText={useTranslate('load_more', 'Load More')}
            onClick={handleClick}
            buttonType="tertiary"
            icon={loadMoreIcon}
            tag="button"
          />
        </div>
      )}
    </>
  );
}

List.propTypes = {
  pagePath: PropTypes.string,
  moduleName: PropTypes.string,
  toplist: PropTypes.shape({
    items: PropTypes.arrayOf(
      PropTypes.shape({
        name: PropTypes.string,
      })
    ),
    tracker: PropTypes.string,
    one_liner: PropTypes.string,
  }),
  hasLoadMoreButton: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.bool]),
  initItemsCount: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.bool]),
  loadItemsCount: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.bool]),
  pageTemplate: PropTypes.string,
  removeInactiveItems: PropTypes.bool,
  template: PropTypes.string,
  verifyIcon: PropTypes.element,
  modulePosition: PropTypes.number,
  
};
