import React from 'react'
import PropTypes from 'prop-types'
import { htmlAttrs, selectSystemProps, getTokensPropType } from '@telus-uds/components-base/server'
import { warn } from '../utils/logger'

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

const Image = React.forwardRef(
  (
    { src, width, height, alt, rounded, loading = 'eager', tokens, theme, variant, ...rest },
    ref
  ) => {
    let { borderRadius } = theme
    const isCircle = rounded === 'circle'
    const isCorners = rounded === 'corners'
    const isSquare = width === height

    if (isCircle && !isSquare) {
      warn(
        'Image',
        'rounded="circle" is not supported for non-square images. Please provide a square image, otherwise the resulting shape will not be a circle.'
      )
    }

    if (isCircle) {
      borderRadius = '50%'
    } else if (isCorners) {
      borderRadius = '4px'
    }

    const style = {
      borderRadius,
      height: height ?? 'auto',
      maxWidth: '100%'
    }
    return (
      <img
        {...selectProps(rest)}
        style={style}
        src={src}
        width={width}
        height={height}
        alt={alt}
        loading={loading}
        ref={ref}
      />
    )
  }
)

Image.displayName = 'Image'

Image.propTypes = {
  ...selectedSystemPropTypes,
  /**
   * The src attribute for the HTML img element.
   */

  src: 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,
  /**
   * The image's width.
   */
  width: PropTypes.number.isRequired,
  /**
   * The image's height.
   */
  height: PropTypes.number,
  /**
   * Loading strategy.
   * @default 'eager'
   * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-loading
   */
  loading: PropTypes.oneOf(['eager', 'lazy']),
  /**
   * Make image render as a circle or with rounded corners.
   */
  rounded: PropTypes.oneOf(['circle', 'corners']),

  tokens: getTokensPropType('Image')
}

Image.displayName = 'Image'

export default Image
