import React, { useState, useEffect } from 'react'
import { Image, View, ImageStyle, ViewStyle, StyleProp } from 'react-native'

import { getCached } from '../image-cache'

type Props = {
  style?: StyleProp<ImageStyle>
  loadingStyle?: StyleProp<ViewStyle>
  uris: (string | undefined)[]
  cacheKey: string
  onError: (error: { nativeEvent: { error: Error } }) => void
}

export function CachedImage(props: Props): React.ReactElement {
  const [uri, setUri] = useState<string | undefined>(undefined)

  useEffect(() => {
    let cancelled = false
    getCached(props.uris, props.cacheKey)
      .then((newUri) => {
        if (!cancelled) {
          setUri(newUri)
        }
      })
      .catch((e) => {
        if (!cancelled) {
          props.onError(e)
        }
      })
    return () => {
      cancelled = true
    }
  }, [props.uris])

  return uri ? (
    <Image source={{ uri }} style={props.style} />
  ) : (
    <View style={[props.style, props.loadingStyle]} />
  )
}
