import React from 'react'
import PropTypes from 'prop-types'
import { A11yText } from '../A11yText/A11yText'
import { Typography } from '../Typography/Typography'
import { Box } from '../Box/Box'
import { Listbox } from '../Listbox/Listbox'

export const Suggestions = React.forwardRef(
  ({ hasResults, items = [], noResults, onClose, onSelect, parentRef }, ref) => {
    const pressableItems = items.map(({ id, ...rest }) => ({
      id,
      onPress: () => onSelect(id),
      ...rest
    }))
    if (items?.length)
      return (
        <>
          <A11yText accessibilityLiveRegion="polite" text={hasResults} />
          <Listbox
            items={pressableItems}
            firstItemRef={ref}
            parentRef={parentRef}
            onClose={onClose}
          />
        </>
      )

    return (
      <Box space={3}>
        {typeof noResults === 'string' ? (
          <>
            <Typography accessibilityLiveRegion="polite" variant={{ size: 'small' }}>
              {noResults}
            </Typography>
          </>
        ) : (
          noResults
        )}
      </Box>
    )
  }
)
Suggestions.displayName = 'Suggestions'
Suggestions.propTypes = {
  hasResults: PropTypes.string.isRequired,
  items: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, label: PropTypes.node }))
    .isRequired,
  noResults: PropTypes.node.isRequired,
  onClose: PropTypes.func.isRequired,
  onSelect: PropTypes.func.isRequired,
  parentRef: PropTypes.object.isRequired
}
