import React from 'react'
import PropTypes from 'prop-types'
import { View } from 'react-native'

import { staticStyles } from './styles'
import { getAdjustedBorderRadius } from './helpers'
import { getWebBackgroundPosition } from './webBackgroundPosition'
import { FallbackImageBackground } from './FallbackImageBackground'

/**
 * Renders the background image layer of a Card on web.
 *
 * `contain` resize mode with both `position` and `align` uses CSS
 * `background-position` so the image is fully visible while honoring the
 * requested anchor. All other cases delegate to `FallbackImageBackground`,
 * which wraps React Native Web's `<ImageBackground>`.
 */
export const SetBackgroundImage = ({
  src,
  alt,
  backgroundImageResizeMode,
  backgroundImagePosition,
  backgroundImageAlign,
  content,
  cardStyle,
  testID
}) => {
  const adjustedBorderRadius = getAdjustedBorderRadius(cardStyle)

  if (backgroundImageResizeMode === 'contain' && backgroundImagePosition && backgroundImageAlign) {
    const backgroundPosition = getWebBackgroundPosition(
      backgroundImagePosition,
      backgroundImageAlign
    )

    const backgroundImageStyle = {
      backgroundImage: `url(${src})`,
      backgroundPosition,
      borderRadius: adjustedBorderRadius
    }

    return (
      <View
        style={[staticStyles.imageBackground, staticStyles.containBackground, backgroundImageStyle]}
        role="img"
        aria-label={alt}
        testID={testID}
      >
        {content}
      </View>
    )
  }

  return (
    <FallbackImageBackground
      src={src}
      alt={alt}
      resizeMode={backgroundImageResizeMode}
      adjustedBorderRadius={adjustedBorderRadius}
      content={content}
      testID={testID}
    />
  )
}

SetBackgroundImage.propTypes = {
  src: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object]),
  alt: PropTypes.string,
  backgroundImageResizeMode: PropTypes.string,
  backgroundImagePosition: PropTypes.string,
  backgroundImageAlign: PropTypes.string,
  content: PropTypes.node,
  cardStyle: PropTypes.shape({
    borderRadius: PropTypes.number,
    borderWidth: PropTypes.number
  }),
  testID: PropTypes.string
}
