import { useState, useEffect } from 'react';
import type { Book } from './Book';
import { deleteBook, getAllBooks } from './books.api';

const BooksList: React.FC = () => {
  const [books, setBooks] = useState<Book[]>([]);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    getAllBooks()
      .then((data) => setBooks(data))
      .catch((error) => {
        console.error(error);
        setError('Es ist ein Fehler aufgetreten');
      });
  }, []);

  async function handleDeleteBook(id: number) {
    try {
      await deleteBook(id);
      setBooks((prevBooks) => prevBooks.filter((book) => book.id !== id));
    } catch (error) {
      console.error(error);
      setError('Löschen des Buches ist fehlgeschlagen');
    }
  }

  if (error) {
    return <div>{error}</div>;
  } else if (books.length === 0) {
    return <div>Keine Bücher gefunden</div>;
  } else {
    return (
      <table>
        <thead>
          <tr>
            <th>Titel</th>
            <th>Autor</th>
            <th>ISBN</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          {books.map((book) => (
            <tr key={book.id}>
              <td>{book.title}</td>
              <td>{book.author}</td>
              <td>{book.isbn}</td>
              <td>
                <button onClick={() => handleDeleteBook(book.id)}>
                  löschen
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }
};

export default BooksList;
