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

import { Platform } from 'react-native'
import { useThemeTokens } from '../ThemeProvider/useThemeTokens'
import { useViewport } from '../ViewportProvider/useViewport'
import { getTokensPropType } from '../utils/props/tokens'
import { variantProp } from '../utils/props/variantProp'
import { tagsToRoles } from '../utils/a11y/semantics'

import { List } from '../List/List'
import { StackWrap } from '../StackView/StackWrap'
import { QuickLinksCard } from './QuickLinksCard'

/**
 * QuickLinks renders a list of interactive items. How it renders these items depends on theme options:
 *  - If the theme returns `list` token as true, it renders an ordered list based on List
 *  - If the theme returns `button` token as true and `list` as false, it renders a wrapping horizontal bar of buttons
 *  - If the theme returns `card` token as true, it wraps the above with a `Card`.
 */
export const QuickLinks = React.forwardRef(
  ({ tokens, variant, listTokens, cardTokens, children, tag = 'ul', ...rest }, ref) => {
    const viewport = useViewport()
    const { dividers, list, card, stackSpace, stackGap, stackJustify } = useThemeTokens(
      'QuickLinks',
      tokens,
      variant,
      {
        viewport
      }
    )

    const itemAccessibilityRole = Platform.select({
      web: ['ul', 'ol'].includes(tag) ? tagsToRoles.li : undefined,
      default: undefined
    })

    const content = (list && (
      <List ref={ref} tokens={listTokens} showDivider={dividers} tag={tag} {...rest}>
        {children}
      </List>
    )) || (
      <StackWrap
        space={stackSpace}
        gap={stackGap}
        tokens={{ justifyContent: stackJustify }}
        tag={tag}
        itemAccessibilityRole={itemAccessibilityRole}
        {...rest}
      >
        {children}
      </StackWrap>
    )

    return card ? <QuickLinksCard tokens={cardTokens}>{content}</QuickLinksCard> : content
  }
)

QuickLinks.displayName = 'QuickLinks'

QuickLinks.propTypes = {
  tokens: getTokensPropType('QuickLinks'),
  /**
   * Custom tokens override for `Card`
   */
  cardTokens: getTokensPropType('Card'),
  /**
   * Custom tokens override for `QuickLinksList`
   */
  listTokens: getTokensPropType('QuickLinksList'),
  /**
   * The HTML tag to render the list as
   */
  tag: PropTypes.string,
  variant: variantProp.propType,
  /**
   * Items rendered in the list.
   */
  children: PropTypes.node
}
