/* eslint-disable no-nested-ternary */
import React, { useState, useContext, useEffect } from 'react';
import PropTypes from 'prop-types';

import Pagination from '~molecules/pagination';
import Items from '~atoms/archive/items';
import Button from '~atoms/button/button';
import { translate } from '~helpers/getters';
import { Context } from '~context/MainProvider';
import styles from './archive.module.scss';

const Archive = ({ module, page, loadMore, gtmClass = '', anchorLabel }) => {
  const [moduleItems, setModuleItems] = useState([...module.items]);
  const updatedModule = { ...module };
  const hasLoadMore = module.pagination_type === 'load_more';
  const { translations } = useContext(Context) || {};

  useEffect(() => {
    if (module.pagination_type === 'load_more') {
      const items = module.items.filter(
        (item, index) => index < parseInt(loadMore ? loadMore.limit : 9)
      );
      setModuleItems(items);
    }
  }, [module, module.items, loadMore]);

  const loadMoreHandler = () => {
    let items = [...module.items];
    if (items.length > moduleItems.length) {
      items = items.filter(
        (item, index) => index < moduleItems.length + parseInt(loadMore ? loadMore.increment : 9)
      );
      setModuleItems(items);
    }
  };

  updatedModule.items = moduleItems;
  return (
    <>
      <Items module={updatedModule} page={page} gtmClass={gtmClass} />
      {hasLoadMore ? (
        module.items.length > updatedModule.items.length && (
          <div className={styles.loadMoreWrapper || ''}>
            <Button
              btnText={translate(translations, 'load_more', 'Load More')}
              onClick={loadMoreHandler}
              buttonType="tertiary"
              buttonSize="m"
              gtmClass="archive-gtm btn-cta"
              isInternalLink={false}
            />
          </div>
        )
      ) : (
        <Pagination
          pagePath={module.rootPath}
          currentPage={module.currentPage}
          totalPages={module.numOfPages}
          anchorLabel={anchorLabel}
        />
      )}
    </>
  );
};

Archive.propTypes = {
  module: PropTypes.shape({
    module_title: PropTypes.string,
    rootPath: PropTypes.string,
    currentPage: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    numOfPages: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
    // eslint-disable-next-line react/forbid-prop-types
    items: PropTypes.arrayOf(PropTypes.object),
    pagination_type: PropTypes.string,
    num_of_items: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  }).isRequired,
  loadMore: PropTypes.shape({
    label: PropTypes.string,
    increment: PropTypes.number,
    limit: PropTypes.number,
    usePrimaryButton: PropTypes.bool,
    useInvertColors: PropTypes.bool,
  }),
  page: PropTypes.shape({
    translations: PropTypes.shape({}),
  }),
  gtmClass: PropTypes.string,
  anchorLabel: PropTypes.string,
};

export default Archive;
