import React from 'react'
import PropTypes from 'prop-types'

import { ButtonBase } from '../Button/ButtonBase'
import { useThemeTokensCallback } from '../ThemeProvider/useThemeTokens'
import { a11yProps } from '../utils/props/a11yProps'
import { copyPropTypes } from '../utils/props/copyPropTypes'
import { getTokensPropType, selectTokens } from '../utils/props/tokens'
import { hrefAttrsProp } from '../utils/props/hrefAttrsProp'
import { linkProps } from '../utils/props/linkProps'
import { variantProp } from '../utils/props/variantProp'
import { withLinkRouter } from '../utils/withLinkRouter'

import { useCopy } from '../utils/useCopy'
import { dictionary } from './dictionary'

const PaginationPageButtonInner = React.forwardRef(
  ({ label, onPress, href, isActive, copy, variant, tokens, ...props }, ref) => {
    const getTokens = useThemeTokensCallback('PaginationPageButton', tokens, variant)

    const getCopy = useCopy({ dictionary, copy })

    const getButtonTokens = (buttonState) => selectTokens('Button', getTokens(buttonState))

    const activeProps = isActive
      ? {
          selected: true,
          ...a11yProps.nonFocusableProps
          // a brute fix for the focus state being stuck on an active item since it becomes non-focusable
          // (see https://github.com/telus/universal-design-system/pull/577#issuecomment-931344107)
        }
      : {}
    const key = isActive ? 'active-item' : undefined

    const accessibilityRole = href !== undefined ? 'link' : 'button'
    const activeLabel = isActive ? ` ${getCopy('currentLabel')}` : ''
    const accessibilityLabel = `${getCopy('goToLabel')} ${label}${activeLabel}`

    const { hrefAttrs, rest } = hrefAttrsProp.bundle(props)
    const buttonProps = {
      accessibilityRole,
      accessibilityLabel,
      onPress,
      href,
      hrefAttrs,
      ...rest
    }

    return (
      <ButtonBase ref={ref} {...buttonProps} tokens={getButtonTokens} key={key} {...activeProps}>
        {label}
      </ButtonBase>
    )
  }
)
PaginationPageButtonInner.displayName = 'PaginationPageButton'

PaginationPageButtonInner.propTypes = {
  ...linkProps.types,
  /**
   * To set custom label for the button
   */
  label: PropTypes.string,
  /**
   * To set `PageButton` to active state
   */
  isActive: PropTypes.bool,
  /**
   * To change the language for labels
   */
  copy: copyPropTypes,
  variant: variantProp.propType,
  tokens: getTokensPropType('PaginationPageButton')
}

// Export unwrapped component for react-docgen to extract info for docsite
export { PaginationPageButtonInner as PaginationPageButtonBase }
export const PaginationPageButton = withLinkRouter(PaginationPageButtonInner)
