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

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

/**
 * Renders the background image layer of a Card on native.
 *
 * `contain` resize mode with both `position` and `align` uses an absolutely
 * positioned `<Image>` over a relative container so the image can be
 * anchored without distortion. All other cases delegate to
 * `FallbackImageBackground`, which wraps React Native's `<ImageBackground>`.
 */
export const SetBackgroundImage = ({
  src,
  alt,
  backgroundImageResizeMode,
  backgroundImagePosition,
  backgroundImageAlign,
  content,
  cardStyle,
  testID
}) => {
  const adjustedBorderRadius = getAdjustedBorderRadius(cardStyle)

  if (backgroundImageResizeMode === 'contain' && backgroundImagePosition && backgroundImageAlign) {
    const positionKey = `${backgroundImagePosition}-${backgroundImageAlign}`
    const positionStyles = nativeStylesMap[positionKey] || {}

    return (
      <View
        style={[staticStyles.containContainer, { borderRadius: adjustedBorderRadius }]}
        testID={testID}
      >
        <Image
          source={src}
          resizeMode={backgroundImageResizeMode}
          style={[staticStyles.containImage, positionStyles]}
          accessible={true}
          accessibilityLabel={alt}
          accessibilityIgnoresInvertColors={true}
        />
        <View style={staticStyles.contentOverlay}>{content}</View>
      </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
}
