import React from 'react'

import Box, { BoxProps } from '../box'
import { useStyleConfig, vui } from '../core'
import Input from '../input'
import T from '../t'
import { ChangeEvent, cs } from '../utils'
import { usePaginationContext } from './context'

/** Displays a number input, which allows quickly jumping between pages. */
export const PaginationGoToPage = vui<'div', BoxProps>((props, ref) => {
  const { className, ...rest } = props
  const { onPageChange, pageCount } = usePaginationContext()
  const styles = useStyleConfig('Pagination', usePaginationContext())

  const onChange = (e: ChangeEvent) => {
    const value = +e.target.value
    if (value >= 1 && value <= pageCount) {
      onPageChange(Math.floor(value))
    }
  }

  return (
    <Box
      centerV
      className={cs('vui-paginationGoToPage', className)}
      lineHeight="normal"
      ref={ref}
      {...styles.goToPage}
      {...rest}
    >
      <T size="sm" weight="medium">
        Go&nbsp;to
      </T>
      <Input max={pageCount} min={1} mx={1} onChange={onChange} size="sm" type="number" w={56} />
      <T size="sm" weight="medium">
        Page
      </T>
    </Box>
  )
})

PaginationGoToPage.displayName = 'PaginationGoToPage'

export default PaginationGoToPage
