import React, { useContext } from "react"
import Pagination from "./pagination"
import DataTableContext from "./context"

/**
 * Allows using client-side pagination with DataTable.
 * Assumes all data is fetched on page load so paging is done within the table component.
 *
 * @see https://tanstack.com/table/latest/docs/guide/pagination#client-side-pagination
 *
 * @deprecated Client-side paging doesn't really make sense for us, so we shouldn't use
 * this. The only reason this exists is to support the legacy behavior of the DataTable.
 */
export default function ClientSidePagination() {
  const { table, data } = useContext(DataTableContext)
  const { pageIndex, pageSize: perPage } = table.getState().pagination

  const firstResultIndex = pageIndex * perPage + 1
  const lastResultIndex =
    perPage * (pageIndex + 1) > data.length
      ? data.length
      : perPage * (pageIndex + 1)

  return (
    <Pagination>
      <Pagination.PageCount>
        {firstResultIndex} - {lastResultIndex} of {data.length}
      </Pagination.PageCount>
      <Pagination.PerPageSelect
        value={perPage}
        onSelect={(perPage) => table.setPageSize(perPage)}
      />
      <Pagination.Navigation
        hasNextPage={table.getCanNextPage()}
        hasPreviousPage={table.getCanPreviousPage()}
        onNextPage={() => table.nextPage()}
        onPreviousPage={() => table.previousPage()}
      />
    </Pagination>
  )
}
