import {useState} from 'react'
import {Button, Dimensions, Pressable, Text, View} from 'react-native'
import DocumentPicker, {
  DocumentPickerResponse,
  types,
} from 'react-native-document-picker'
import Video from 'react-native-video'
import {backgroundColor} from './constants'

const buttonWidth = '45%'

export default function App() {
  const [files, setFiles] = useState<DocumentPickerResponse[]>([])
  const [selected, setSelected] = useState(0)
  const [paused, setPaused] = useState(false)
  const [width, setWidth] = useState(0)

  const height = Dimensions.get('screen').height

  const pick = async () => {
    const picked = await DocumentPicker.pickMultiple({type: types.video})
    setSelected(0)
    console.log(`Picked ${picked.length} files.`)
    setFiles(picked)
  }

  const prev = () => {
    if (selected <= 0) return
    setSelected(selected - 1)
    setPaused(false)
  }

  const next = () => {
    if (selected >= files.length - 1) return
    setSelected(selected + 1)
    setPaused(false)
  }

  return (
    <View
      style={{
        backgroundColor,
        justifyContent: 'center',
        alignItems: 'center',
        flex: 1,
        flexGrow: 1,
        padding: 10,
      }}>
      {files.length > 0 ? (
        <View style={{alignItems: 'center'}}>
          <Pressable onLongPress={pick} onPress={() => setPaused(!paused)}>
            <Video
              paused={paused}
              style={{
                height: height - height * 0.25,
                width,
                alignItems: 'center',
              }}
              source={{uri: files[selected].uri}}
              resizeMode="contain"
              onLoad={response => {
                setWidth(response.naturalSize.width)
              }}
            />
          </Pressable>
          <Text
            style={{
              color: 'white',
              margin: 10,
            }}>
            {files[selected].name} ({selected + 1}/ {files.length})
          </Text>
          <View style={{flexDirection: 'row', justifyContent: 'space-around'}}>
            <View style={{width: buttonWidth, marginRight: 10}}>
              <Button title="Prev" disabled={selected <= 0} onPress={prev} />
            </View>
            <View style={{width: buttonWidth}}>
              <Button
                title="Next"
                disabled={selected >= files.length - 1}
                onPress={next}
              />
            </View>
          </View>
        </View>
      ) : (
        <View style={{width: buttonWidth}}>
          <Button title="Pick" onPress={pick} />
        </View>
      )}
    </View>
  )
}
