import { IPageContext } from "../../types";
import { Link } from "gatsby";
import * as classNames from "classnames";
import * as styles from "./styles.module.scss";
import kebabCase from "lodash/kebabCase";
import React from "react";

interface IProps {
  pageContext: IPageContext;
}

const Pagination = ({ pageContext }: IProps) => {
  const { currentPage, numPages, tag } = pageContext;
  const isFirst = currentPage === 1;
  const isLast = currentPage === numPages;
  const tagSlugLocale = "categorie";
  const tagSlug = tag ? `/${tagSlugLocale}/${kebabCase(tag)}` : "";
  const prevPage =
    currentPage - 1 === 1 ? `` : `${tagSlug}/${(currentPage - 1).toString()}`;
  const nextPage =
    currentPage === 1
      ? `${tagSlug}/2`
      : `${tagSlug}/${(currentPage + 1).toString()}`;
  const currentPageAdjusted = currentPage - 1;

  return (
    <React.Fragment>
      {numPages > 1 && (
        <nav className={styles.pagination} role="navigation">
          <ul className={styles.list}>
            {!isFirst && (
              <li className={styles.item}>
                <Link
                  className={classNames({
                    [styles.link]: true
                  })}
                  to={prevPage}
                  rel="prev"
                >
                  <span className={styles.text}>&larr;</span>
                </Link>
              </li>
            )}
            {Array.from({ length: numPages }, (value, i) => (
              <li className={styles.item} key={`pagination-number${i + 1}`}>
                <Link
                  className={classNames({
                    [styles.link]: true,
                    [styles.active]: currentPageAdjusted === i
                  })}
                  activeClassName={styles.active}
                  to={`${tagSlug}/${i === 0 ? "" : i + 1}`}
                >
                  <span className={styles.text}>{i + 1}</span>
                </Link>
              </li>
            ))}
            {!isLast && (
              <li className={styles.item}>
                <Link
                  className={classNames({
                    [styles.link]: true
                  })}
                  to={nextPage}
                  rel="next"
                >
                  <span className={styles.text}>&rarr;</span>
                </Link>
              </li>
            )}
          </ul>
        </nav>
      )}
    </React.Fragment>
  );
};

export default Pagination;
