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

import { useThemeTokensCallback } from '../ThemeProvider/useThemeTokens'
import { selectTokens, getTokensPropType } from '../utils/props/tokens'
import { linkProps } from '../utils/props/linkProps'
import { LinkBase } from './LinkBase'

/**
 * `ChevronLink` is a convenience wrapper around the `Link` component to enable "directional" links.
 * It effectively pre-binds left and right icons, and a directional translation of the icon on hover.
 *
 * ChevronLink is not intended to be deeply themable; variants passed to ChevronLink are forwarded to Link.
 */
export const ChevronLink = React.forwardRef(
  ({ direction = 'right', children, tokens = {}, variant, dataSet, ...otherlinkProps }, ref) => {
    const getChevronTokens = useThemeTokensCallback('ChevronLink', tokens, variant)
    const applyChevronTokens = (linkState) => {
      const { leftIcon, rightIcon, iconDisplace, height, fontSize, ...otherTokens } =
        getChevronTokens(linkState)

      const linkTokens = selectTokens('Link', otherTokens)

      return {
        ...linkTokens,
        height,
        blockFontSize: tokens.fontSize ?? fontSize,
        icon: direction === 'right' ? rightIcon : leftIcon,
        iconTranslateX: iconDisplace * (direction === 'right' ? 1 : -1) || 0
      }
    }

    const getTokens = useThemeTokensCallback('Link', applyChevronTokens, variant)

    return (
      <LinkBase
        {...otherlinkProps}
        useMeasuredMobileIconLayout
        iconPosition={direction}
        tokens={getTokens}
        dataSet={dataSet}
        ref={ref}
      >
        {children}
      </LinkBase>
    )
  }
)

ChevronLink.displayName = 'ChevronLink'
ChevronLink.propTypes = {
  ...LinkBase.propTypes,
  /**
   * Text content of the link.
   */
  children: PropTypes.node,
  variant: PropTypes.exact({
    size: PropTypes.oneOf(['large', 'small', 'micro']),
    style: PropTypes.oneOf(['inline', 'subtle', 'feature', 'danger', 'inverse'])
  }),
  ...linkProps.types,
  tokens: getTokensPropType('ChevronLink', 'Link'),
  /**
   * Changes direction of chevron icon
   */
  direction: PropTypes.oneOf(['left', 'right'])
}
