import React from "react";

type PaginatorCoreProps = {
  activePage: number;
  firstPage?: Function;
  prevPage: Function;
  lastPage?: Function;
  nextPage: Function;
  dots: Function;
  showPages: number;
  pageCount: number;
  page: Function;
};

export default function PaginatorCore(props: PaginatorCoreProps) {
  if (props.pageCount <= 1) {
      return null;
  }

  const firstPage = props.activePage !== 1 && props.firstPage && props.firstPage(1);
  const prevPage = props.activePage !== 1 && props.prevPage && props.prevPage(props.activePage - 1);

  const showPages = props.showPages || props.pageCount;
  const middlePage = showPages / 2;

  const startPage = Math.max(0, Math.floor(props.activePage - middlePage));

  const pages = [...Array(Math.min(showPages, props.pageCount - startPage))]
    .fill(0)
    .map((_, index) => startPage + 1 + index);

  const pageElements = pages.map(page => props.page(page));

  const nextPage = props.activePage !== props.pageCount && props.nextPage && props.nextPage(props.activePage + 1);
  const lastPage = props.activePage !== props.pageCount && props.lastPage && props.lastPage(props.pageCount);

  return <React.Fragment>
      {firstPage}
      {prevPage}

      {pages[0] !== 1 && props.dots(1)}

      {pageElements}

      {pages[pages.length - 1] !== props.pageCount && props.dots(props.pageCount)}

      {nextPage}
      {lastPage}
  </React.Fragment>;
}
