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

import { viewports } from '@telus-uds/system-constants'
import { useResponsiveProp } from '../utils/useResponsiveProp'

export const ResponsiveProp = ({ min = 'xs', max, children }) => {
  const byViewports = { [min]: children }
  if (max && max !== 'xl') {
    // Stop returning children at the viewport one above 'max' or greater
    const maxIndex = viewports.keys.indexOf(max)
    const maxPlusOne = maxIndex >= 0 ? viewports.keys[maxIndex + 1] : null
    if (maxPlusOne) byViewports[maxPlusOne] = null
  }
  const responsiveProp = useResponsiveProp(byViewports, null)
  return <>{responsiveProp}</>
}

ResponsiveProp.displayName = 'Responsive'

ResponsiveProp.propTypes = {
  /**
   * To hide children of `Responsive` if the current viewport is smaller than `min`
   */
  min: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']),
  /**
   * To hide children of `Responsive` if the current viewport is larger than `max`
   */
  max: PropTypes.oneOf(['sm', 'md', 'lg', 'xl']),
  children: PropTypes.node.isRequired
}
