import React, { PureComponent } from 'react'
import { Image, ImageStyle, type StyleProp, StyleSheet } from 'react-native'
import PropTypes from 'prop-types'
import { ImageRatios, ImageRatioStyle } from '@adalo/constants'

import { applyImgixParameters } from 'utils/imgix'
import { CellProps, ImageValue } from './TableTypes'

class ImageCell extends PureComponent<CellProps> {
  static contextTypes = {
    getImageUploadsBaseURL: PropTypes.func,
  }

  render() {
    const { cell } = this.props
    const { getImageUploadsBaseURL } = this.context

    const imageValue = cell.value as ImageValue
    const imageRatio = cell.binding?.format?.imageRatio

    if (!imageValue || !imageRatio) {
      return null
    }

    const size = ImageRatioStyle[imageRatio]

    const imageURL = applyImgixParameters(
      `${getImageUploadsBaseURL()}/${imageValue.url}`,
      size
    )

    const imageStyle: StyleProp<ImageStyle>[] = [
      styles.image,
      imageRatio === ImageRatios.circle && styles.imageCircle,
      size,
    ]

    return (
      <Image source={{ uri: imageURL }} style={imageStyle} resizeMode="cover" />
    )
  }
}

const styles = StyleSheet.create({
  container: {
    justifyContent: 'center',
    alignItems: 'center',
    overflow: 'hidden',
  },
  image: {
    borderRadius: 4,
  },
  imageCircle: {
    borderRadius: 999,
  },
})

export default ImageCell
