import React from 'react'
import PropTypes from 'prop-types'
import { StackWrap } from '../StackView/StackWrap'
import { useViewport } from '../ViewportProvider/useViewport'
import { useThemeTokens } from '../ThemeProvider/useThemeTokens'
import { a11yProps } from '../utils/props/a11yProps'
import { getTokensPropType } from '../utils/props/tokens'
import { selectSystemProps } from '../utils/props/selectSystemProps'
import { variantProp } from '../utils/props/variantProp'
import { viewProps } from '../utils/props/viewProps'

// pass through and type relevant system props - add more sets for interactive components
const [selectProps, selectedSystemPropTypes] = selectSystemProps([a11yProps, viewProps])

const isQuickListItem = (element) => {
  const elementName = element?.type?.displayName || element?.type?.name
  return Boolean(elementName.match(/QuickLinksFeatureItem/))
}

/**
 * QuickLinksFeature renders a list of interactive items.
 *  - This is the base component that is used as a wrapper and accepts a List of `QuickLinksFeatureItem`
 */
export const QuickLinksFeature = React.forwardRef(
  ({ tokens, variant, tag = 'ul', children, ...rest }, ref) => {
    const viewport = useViewport()
    const { stackGap, stackJustify, stackSpace } = useThemeTokens(
      'QuickLinksFeature',
      tokens,
      variant,
      { viewport }
    )

    const items = React.Children.map(children, (child) => {
      if (isQuickListItem(child)) {
        return React.cloneElement(child, child.props)
      }

      return null
    })

    return (
      <StackWrap
        space={stackSpace}
        gap={stackGap}
        tokens={{ justifyContent: stackJustify }}
        tag={tag}
        ref={ref}
        {...selectProps(rest)}
      >
        {items}
      </StackWrap>
    )
  }
)

QuickLinksFeature.displayName = 'QuickLinksFeature'

QuickLinksFeature.propTypes = {
  ...selectedSystemPropTypes,
  tokens: getTokensPropType('QuickLinksFeature'),
  variant: variantProp.propType,
  /**
   * Default wrapper tag, by default it's "ul"
   */
  tag: PropTypes.string,
  /**
   * QuickLinksFeatureItem component
   */
  children: PropTypes.node
}
