import { useState, useEffect } from 'react';
import { FlatList, Text } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import type { Book } from './Book';
import {
  Container,
  Headline,
  Separator,
  ListItem,
  Search,
} from './List.styles';

const List: React.FC = () => {
  const [filter, setFilter] = useState('');
  const [books, setBooks] = useState<Book[]>([]);

  useEffect(() => {
    fetch('http://localhost:3001/books')
      .then((response) => response.json())
      .then((data) => setBooks(data));
  }, []);

  const filteredBooks = books.filter((book) =>
    book.title.toLowerCase().includes(filter.toLowerCase()),
  );

  return (
    <SafeAreaView style={{ flex: 1 }} edges={['top', 'left', 'right']}>
      <Container>
        <Headline>Bücherverwaltung</Headline>

        <Search
          autoCapitalize="none"
          value={filter}
          onChangeText={(text: string) => setFilter(text)}
          placeholder="Suche"
          placeholderTextColor="grey"
        />

        <FlatList<Book>
          data={filteredBooks}
          keyExtractor={(item) => item.id.toString()}
          ItemSeparatorComponent={() => <Separator />}
          renderItem={({ item }) => (
            <ListItem>
              <Text style={{ color: 'black' }}>{item.title}</Text>
            </ListItem>
          )}
        />
      </Container>
    </SafeAreaView>
  );
};

export default List;
