/* eslint-disable array-callback-return */
/* eslint-disable react/forbid-prop-types */
import React, { useContext } from 'react';
import PropTypes from 'prop-types';
import { BiSitemap } from '@react-icons/all-files/bi/BiSitemap';
import { IoMdLink } from '@react-icons/all-files/io/IoMdLink';
// eslint-disable-next-line import/no-extraneous-dependencies
import Masonry from 'react-masonry-css';
import { Context } from '~context/MainProvider';
import { translate } from '~helpers/getters';
import styles from './sitemap.module.scss';
import Link from '~hooks/link';

const Sitemap = ({
  pageContext,
  templateIcon = <BiSitemap title="Sitemap Icon" />,
  linkIcon = <IoMdLink title="Link Icon" />,
  breakpointCols = 3,
}) => {
  const { templates, sitemapData } = pageContext;
  const { translations } = useContext(Context) || {};

  const getTemplateName = (template) => {
    const templateName = translate(
      translations,
      templates[template].short_name,
      templates[template].short_name.replace('_', ' ')
    );
    const templatePages = sitemapData[template];
    const templatePagesCount = templatePages && templatePages.length;

    return (
      templatePagesCount !== undefined && (
        <div>
          <div>
            {templateIcon && templateIcon}
            <span>{templatePagesCount}</span>
          </div>
          <span>{templateName}</span>
        </div>
      )
    );
  };

  const getTemplatePages = (template) => {
    if (sitemapData[template]) {
      const pageList = Object.keys(sitemapData[template]).map((page) => {
        if (page !== undefined) {
          const pageObj = sitemapData[template][page];
          return (
            <li key={page}>
              {linkIcon && linkIcon}
              <Link to={pageObj.path} title={pageObj.title}>
                {pageObj.title}
              </Link>
            </li>
          );
        }
      });
      return <ul>{pageList}</ul>;
    }
  };

  return (
    <Masonry
      breakpointCols={breakpointCols}
      className={styles.container || ''}
      columnClassName={styles.list}
    >
      {Object.keys(sitemapData).map((template) => (
        <ul key={template}>
          {getTemplateName(template)}
          {getTemplatePages(template)}
        </ul>
      ))}
    </Masonry>
  );
};

Sitemap.propTypes = {
  pageContext: PropTypes.shape({
    sitemapData: PropTypes.object,
    templates: PropTypes.object,
  }),
  templateIcon: PropTypes.element,
  linkIcon: PropTypes.element,
  breakpointCols: PropTypes.number,
};

export default Sitemap;
