import { StyleSheet, FlatList, Text } from 'react-native'
import { useState, useEffect } from 'react'
import Note from './Note'
import Menu from './Menu'

const List = ({ session, setSession, showError, setEdit }) => {
  const [list, setList] = useState()
  const [loading, setLoading] = useState(true)

  const fetchNotes = async () => {
    setLoading(true)
    try {
      const response = await fetch('https://apps.pruss.it/api/notes', { 'Cookie': session.cookies } )
      const data = await response.json()
      setList(data)
    } catch(e) {
      showError('Error while fetching notes')
    }
    setLoading(false)
  }

  useEffect(() => {
    setLoading(true)
    fetchNotes()
  }, [])

  return (
    <>
      <Menu
        session={session}
        setSession={setSession}
        showError={showError}
        setEdit={setEdit}
      />
      {
        loading || list === undefined
          ? <Text style={styles.text}>Loading notes...</Text>
          : (
            <FlatList
              data={list.sort((a,b) => new Date(b.updated_at) - new Date(a.updated_at))}
              renderItem={({item}) => <Note note={item} setEdit={setEdit} />}
              ListEmptyComponent={<Text style={styles.text}>You don't have any notes</Text>}
              onRefresh={fetchNotes}
              refreshing={loading}
            />
          )
      }
    </>
  )
}

const styles = StyleSheet.create({
  text: {
    color: 'white',
    padding: 20,
  },
  menu: {
    backgroundColor: 'lightgrey',
    height: 55,
    width: '100%',
    flexDirection: 'row',
    alignItems: 'flex-end',
    justifyContent: 'space-between',
    padding: 10,
  },
  menuText: {
    fontWeight: 'bold',
    paddingHorizontal: 10,
  },
});

export default List;
