import React, { useState } from 'react'
import { StyleProp, ImageStyle } from 'react-native'

import { ImageGradientBackground } from './ImageGradientBackground'
import { CachedImage } from './CachedImage'
import { colors } from '../Colors'

type Props = {
  uris: (string | undefined)[]
  cacheKey: string
  gradientString: string
  style?: StyleProp<ImageStyle>
}

export function CachedImageWithFallback({
  uris,
  cacheKey,
  gradientString,
  style,
}: Props): React.ReactElement {
  const [hasImage, setHasImage] = useState(true)
  return hasImage ? (
    <CachedImage
      uris={uris}
      cacheKey={cacheKey}
      onError={() => setHasImage(false)}
      style={style}
      loadingStyle={{ backgroundColor: colors.darkGray }}
    />
  ) : (
    <ImageGradientBackground string={gradientString} style={style} />
  )
}
