import { StyleSheet, Text } from 'react-native'
import SwipeableFlatList from 'react-native-swipeable-list'
import { useState, useEffect } from 'react'
import { getList } from '../utils/api'
import Note from './Note'
import Menu from './Menu'
import RemoveNoteButton from './RemoveNoteButton'
import { handleRemove } from "../utils/helpers";

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

  const sortFn = (a, b) => {
    const d = sort % 2 ? -1 : 1
    switch (sort) {
      case 0: case 1: return d * (new Date(b.updated_at) - new Date(a.updated_at))
      case 2: case 3: return d * (new Date(b.created_at) - new Date(a.created_at))
      case 4: case 5: return d * a.title.toLowerCase().localeCompare(b.title.toLowerCase())
    }
  }

  const fetchNotes = async () => {
    setLoading(true)
    try {
      const response = await getList({ session })
      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}
        sort={sort}
        setSort={setSort}
      />
      {
        loading || list === undefined
          ? <Text style={styles.text}>Loading notes...</Text>
          : (
            <SwipeableFlatList
              data={list.sort(sortFn)}
              renderItem={({item}) => <Note note={item} setEdit={setEdit} />}
              keyExtractor={item => item._id}
              ListEmptyComponent={<Text style={styles.text}>You don't have any notes</Text>}
              onRefresh={fetchNotes}
              refreshing={loading}
              maxSwipeDistance={80}
              bounceFirstRowOnMount={false}
              renderQuickActions={({item}) => RemoveNoteButton({
                removeNote: () => handleRemove({ note: item, session, fetchNotes, setLoading, showError })
              })}
            />
          )
      }
    </>
  )
}

const styles = StyleSheet.create({
  text: {
    color: 'white',
    padding: 20,
  },
});

export default List;
