import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { usePaginationContext } from "./pagination-context";

/** Props for Pagination.Next. */
export interface PaginationNextProps extends JSX.ButtonHTMLAttributes<HTMLButtonElement> {
  children?: JSX.Element;
}

/** Button that navigates to the next page. Disabled on the last page. */
export function PaginationNext(props: PaginationNextProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children", "onClick"]);
  const ctx = usePaginationContext();

  const isDisabled = () => ctx.page() >= ctx.totalPages();

  const handleClick: JSX.EventHandler<HTMLButtonElement, MouseEvent> = (e) => {
    if (isDisabled()) return;
    if (typeof local.onClick === "function") local.onClick(e);
    ctx.onPageChange(ctx.page() + 1);
  };

  return (
    <button
      type="button"
      aria-label="Go to next page"
      disabled={isDisabled()}
      onClick={handleClick}
      {...rest}
    >
      {local.children ?? "Next"}
    </button>
  );
}
