import {useMemo, useState} from 'react'
import {Dimensions, Image, Pressable, Text, View} from 'react-native'
import {DocumentPickerResponse, types} from 'react-native-document-picker'
import Video from 'react-native-video'

export default function Item({
  files,
  onLongPress,
  selected,
  paused,
  setPaused,
}: {
  files: DocumentPickerResponse[]
  onLongPress: () => void
  selected: number
  paused: boolean
  setPaused: (value: boolean) => void
}) {
  const [width, setWidth] = useState(0)
  const screenHeight = Dimensions.get('screen').height
  const file = useMemo(() => files[selected], [files, selected])

  const video = (
    <Pressable onLongPress={onLongPress} onPress={() => setPaused(!paused)}>
      <Video
        paused={paused}
        style={{
          height: screenHeight - screenHeight * 0.25,
          width,
          alignItems: 'center',
        }}
        source={{uri: file.uri}}
        resizeMode="contain"
        onLoad={response => {
          setWidth(response.naturalSize.width)
        }}
      />
    </Pressable>
  )

  const image = (
    <Pressable onLongPress={onLongPress}>
      <Image
        source={{
          uri: file.uri,
          width: 300,
          height: screenHeight - screenHeight * 0.25,
        }}
        resizeMode="contain"
        onLoad={({nativeEvent}) => setWidth(nativeEvent.source.width)}
      />
    </Pressable>
  )

  return (
    <View style={{alignItems: 'center'}}>
      {file.type?.includes('video') ? video : image}
      <Text
        style={{
          color: 'white',
          margin: 10,
        }}>
        {file.name} ({selected + 1}/ {files.length})
      </Text>
    </View>
  )
}
