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

const buttonWidth = '45%'

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

  const pick = async () => {
    const picked = await DocumentPicker.pickMultiple({
      type: [types.video, types.images],
    })
    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 ? (
        <>
          <Item
            paused={paused}
            setPaused={setPaused}
            onLongPress={pick}
            selected={selected}
            files={files}
          />
          <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>
        </>
      ) : (
        <Pressable
          onPress={pick}
          style={{height: '100%', justifyContent: 'center'}}>
          <Text style={{color: 'white', fontSize: 24}}>Select video(s)...</Text>
        </Pressable>
      )}
    </View>
  )
}
