import { StatusBar } from 'expo-status-bar'
import { StyleSheet, SafeAreaView, Text } from 'react-native'
import { useState, useEffect } from 'react'
import AsyncStorage from '@react-native-async-storage/async-storage'
import Main from './components/Main'
import Login from './components/Login'
import Loader from './components/Loader'

export default function App() {
  const [session, setSession] = useState()
  const [error, setError] = useState(null)

  const showError = (e) => {
    setError(e)
    setTimeout(() => { setError(null) }, 2000)
  }

  useEffect(() => {
    AsyncStorage.getItem('session')
      .then(session => setSession(JSON.parse(session)))
      .catch(() => setSession(null))
  }, [])

  if (error || session === undefined) return (
    <SafeAreaView style={styles.container}>
      {error
        ? <Text style={styles.error}>{error}</Text>
        : <Loader />}
    </SafeAreaView>
  )

  return (
    <SafeAreaView style={styles.container}>
      {
        session === null
          ? <Login setSession={setSession} showError={showError} />
          : <Main session={session} setSession={setSession} showError={showError} />
      }
      <StatusBar style="auto" />
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#000',
  },
  error: {
    color: 'red',
  }
})
