import React, { ReactNode } from "react";
import classNames from "classnames";
import { BoxProps } from "../Box";
import { Flex } from "../Flex";
import { Text } from "../Text";
import { bem } from "../../utilities/bem";

const cn = "Pagination";

export interface PaginationProps extends BoxProps {
  onPageChange: (pageNumber: number) => any;
  currentPageNumber: number;
  itemsPerPage: number;
  totalItems: number;
}

interface PageButtonProps {
  children: ReactNode;
  onClick: () => void;
  className?: string;
}

const PageButton = ({ className, ...rest }: PageButtonProps) => {
  return <button className={className} type="button" {...rest} />;
};

const Pagination = (props: PaginationProps) => {
  const {
    currentPageNumber,
    itemsPerPage,
    totalItems,
    onPageChange,
    className,
    ...rest
  } = props;

  const numPages = Math.ceil(totalItems / itemsPerPage);
  const pageList = new Array(numPages).fill(0);

  const handleClick = (newPageNumber: number) => {
    if (newPageNumber > 0 && newPageNumber <= pageList.length) {
      onPageChange(newPageNumber);
    }
  };

  const visibileItems =
    currentPageNumber === numPages
      ? totalItems - (numPages - 1) * itemsPerPage
      : itemsPerPage;

  return (
    <Flex className={classNames([bem(cn), className])} {...rest}>
      {pageList.map((_, index) => {
        const pageNum = index + 1;

        return (
          <PageButton
            key={pageNum}
            onClick={() => handleClick(pageNum)}
            className={classNames(
              bem(cn, { e: "page" }),
              pageNum === currentPageNumber &&
                bem(cn, { e: "page", m: "active" }),
            )}
          >
            {pageNum}
          </PageButton>
        );
      })}

      <Text as="span" className={bem(cn, { e: "text" })}>
        {`Showing ${visibileItems} of ${totalItems} results`}
      </Text>
    </Flex>
  );
};

export { Pagination };
