import { useState } from "react"

export interface Page {
  pageSize: number
  pageNum: number
}

export const defaultPageSize = 20
export const defaultPageSizeOptions = [10, 20, 50, 100]
export type PageSizeOptions = typeof defaultPageSizeOptions[number]

export const defaultPage = {
  pageSize: defaultPageSize,
  pageNum: 1
}
export function usePage(pageSize?: number): [Page, React.Dispatch<React.SetStateAction<Page>>, (pageNum: number) => void] {
  const [page, setPage] = useState<Page>(() => ({
    pageSize: pageSize ?? defaultPageSize, pageNum: 1,
  }))
  const gotoPage = (pageNum: number) => {
    setPage(prev => ({ ...prev, pageNum }))
  }
  return [page, setPage, gotoPage]
}

export type PageType = ReturnType<typeof usePage>[0]


export function paginate<T>(list: T[] | undefined, page: Page) {
  if (list) { 
    const { pageSize, pageNum } = page
    const start = (pageNum - 1) * pageSize
    const end = start + pageSize
    return list.slice(start, end)
  }
  return list
}