import React from 'react'
import PropTypes from 'prop-types'
import { selectSystemProps } from '@telus-uds/components-base'
import { viewports } from '@telus-uds/system-constants'
import { htmlAttrs, contentfulProps } from '../utils'

const [selectProps, selectedSystemPropTypes] = selectSystemProps([htmlAttrs, contentfulProps])

const staticStyles = {
  image: { display: 'block', width: '100%' }
}

/**
 * Provide different image sources for different screen sizes.
 */
const ResponsiveImage = React.forwardRef(
  (
    { xsSrc, smSrc, mdSrc, lgSrc, xlSrc, fallbackSrc, alt, loading = 'eager', dataSet, ...rest },
    ref
  ) => {
    return (
      <picture {...selectProps(rest)} ref={ref} {...dataSet}>
        <source srcSet={xlSrc} media={`(min-width: ${viewports.map.get(viewports.xl)}px)`} />
        <source srcSet={lgSrc} media={`(min-width: ${viewports.map.get(viewports.lg)}px)`} />
        <source srcSet={mdSrc} media={`(min-width: ${viewports.map.get(viewports.md)}px)`} />
        <source srcSet={smSrc} media={`(min-width: ${viewports.map.get(viewports.sm)}px)`} />
        <source srcSet={xsSrc} media={`(max-width: ${viewports.map.get(viewports.sm) - 1}px)`} />
        <img src={fallbackSrc} alt={alt} style={staticStyles.image} loading={loading} />
      </picture>
    )
  }
)

ResponsiveImage.displayName = 'ResponsiveImage'

ResponsiveImage.propTypes = {
  ...selectedSystemPropTypes,
  /**
   * The src attribute used for screen widths up to 575px
   */
  xsSrc: PropTypes.string.isRequired,
  /**
   * The src attribute used for screen widths greater than 576px
   */
  smSrc: PropTypes.string.isRequired,
  /**
   * The src attribute used for screen widths greater than 768px
   */
  mdSrc: PropTypes.string,
  /**
   * The src attribute used for screen widths greater than 992px
   */
  lgSrc: PropTypes.string,
  /**
   * The src attribute used for screen widths greater than 1200px
   */
  xlSrc: PropTypes.string,
  /**
   * The src attribute used for browsers that don't support responsive images (InternetExplorer)
   */
  fallbackSrc: PropTypes.string.isRequired,
  /**
   * The alt attribute for the HTML img element. Setting this attribute to an empty string (alt="") indicates that this image is not a key part of the content, and that non-visual browsers may omit it from rendering.
   */
  alt: PropTypes.string.isRequired,
  /**
   * Loading strategy.
   * @default 'eager'
   * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-loading
   */
  loading: PropTypes.oneOf(['eager', 'lazy']),
  /**
   * The dataSet prop allows to pass data-* attributes element to the component.
   */
  dataSet: PropTypes.object
}

export default ResponsiveImage
