import clsx from "clsx";
import usePagination, {
  UsePaginationItem,
  UsePaginationProps,
} from "libs/hooks/usePagination";

import PaginationItem, { PaginationItemProps } from "./PaginationItem";

import styles from "./index.module.scss";
import { forwardRef } from "react";

export interface PaginationProps extends UsePaginationProps {
  className?: string;
  /**
   * Accepts a function which returns a string value that provides a user-friendly name for the current page.
   * This is important for screen reader users.
   *
   * For localization purposes, you can use the provided [translations](/material-ui/guides/localization/).
   * @param {string} type The link or button type to format ('page' | 'first' | 'last' | 'next' | 'previous'). Defaults to 'page'.
   * @param {number} page The page number to format.
   * @param {bool} selected If true, the current page is selected.
   * @returns {string}
   */
  getItemAriaLabel?: typeof defaultGetAriaLabel;
  /**
   * Render the item.
   * @param {UsePaginationItem} params The props to spread on a PaginationItem.
   * @returns {ReactNode}
   * @default (item) => <PaginationItem {...item} />
   */
  renderItem?: (params: UsePaginationItem) => React.ReactNode;
}

function defaultGetAriaLabel(
  type: UsePaginationItem["type"],
  page: number | null,
  selected: boolean
) {
  if (type === "page") {
    return `${selected ? "" : "Go to "}page ${page}`;
  }
  return `Go to ${type} page`;
}

const Pagination = forwardRef<HTMLDivElement, PaginationProps>(
  function Pagination(props, ref) {
    const {
      boundaryCount = 1,
      className,
      count = 1,
      defaultPage = 1,
      disabled = false,
      getItemAriaLabel = defaultGetAriaLabel,
      hideNextButton = false,
      hidePrevButton = false,
      onChange,
      renderItem = (item: PaginationItemProps) => <PaginationItem {...item} />,

      ...other
    } = props;

    const { items } = usePagination({ ...props, componentName: "Pagination" });

    return (
      <nav
        aria-label="pagination navigation"
        className={clsx(styles.pages, className)}
        ref={ref}
        {...other}
      >
        <ul className={styles.inner}>
          {items.map((item, index) => (
            <li key={index}>
              {renderItem({
                ...item,
                "aria-label": getItemAriaLabel(
                  item.type,
                  item.page,
                  item.selected
                ),
              })}
            </li>
          ))}
        </ul>
      </nav>
    );
  }
);
export default Pagination;
