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

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

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

  const isDisabled = () => ctx.page() <= 1;

  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 previous page"
      disabled={isDisabled()}
      onClick={handleClick}
      {...rest}
    >
      {local.children ?? "Previous"}
    </button>
  );
}
