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

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

export function CachedImage({
  uris,
  cacheKey,
  onError,
  style,
  loadingStyle,
}: {
  style?: StyleProp<ImageStyle>
  loadingStyle?: StyleProp<ViewStyle>
  uris: (string | undefined)[]
  cacheKey: string
  onError: (error: { nativeEvent: { error: Error } }) => void
}): React.ReactElement {
  const [uri, setUri] = useState<string | undefined>(undefined)

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

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