import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { PaginationContextProvider, type PaginationContextValue } from "./pagination-context";
import { PaginationEllipsis } from "./pagination-ellipsis";
import { PaginationItems } from "./pagination-items";
import { PaginationNext } from "./pagination-next";
import { PaginationPrevious } from "./pagination-previous";
import { usePaginationContext } from "./pagination-context";

/** Props for the Pagination root component. */
export interface PaginationRootProps extends JSX.HTMLAttributes<HTMLElement> {
  /** Current page number (1-based). */
  page: number;
  /** Total number of pages. */
  totalPages: number;
  /** Called when the user navigates to a different page. */
  onPageChange: (page: number) => void;
  /** Number of sibling pages shown around the current page. @default 1 */
  siblingCount?: number;
  children: JSX.Element;
}

/**
 * Root container for Pagination. Provides page state to all parts.
 */
export function PaginationRoot(props: PaginationRootProps): JSX.Element {
  const [local, rest] = splitProps(props, [
    "page",
    "totalPages",
    "onPageChange",
    "siblingCount",
    "children",
  ]);

  const ctx: PaginationContextValue = {
    page: () => local.page,
    totalPages: () => local.totalPages,
    onPageChange: (p) => local.onPageChange(p),
    siblingCount: () => local.siblingCount ?? 1,
  };

  return (
    <PaginationContextProvider value={ctx}>
      <nav aria-label="pagination" {...rest}>
        {local.children}
      </nav>
    </PaginationContextProvider>
  );
}

/** Compound Pagination component with all sub-components as static properties. */
export const Pagination = Object.assign(PaginationRoot, {
  Previous: PaginationPrevious,
  Next: PaginationNext,
  Items: PaginationItems,
  Ellipsis: PaginationEllipsis,
  useContext: usePaginationContext,
});
