import { useState, useEffect } from 'react';
import { getBooks } from '../api/books';
import { Link } from 'react-router-dom';

export default function Books() {
  const [books, setBooks] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    getBooks()
      .then((response) => {
        console.log(response.data); 
        setBooks(response.data.content);
      })
      .catch((err) => {
        console.error(err);
        setError("Impossible de charger les livres.");
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  if (loading) return <main><p>Chargement…</p></main>;
  if (error) return <main><p>{error}</p></main>;

  return (
    <main>
      <h1>Catalogue</h1>
      <Link to="/books/new">+ Ajouter un livre</Link>
      <ul>
        {books.map((book) => (
          <li key={book.isbn}>
            <strong>{book.title}</strong> - {book.author}
          </li>
        ))}
      </ul>
    </main>
  );
}