import { useEffect, useState } from 'react';

type Book = {
  id: number;
  title: string;
};

type Props = {
  token: string | undefined;
  refreshToken: () => Promise<void>;
};

const BooksList: React.FC<Props> = ({ token, refreshToken }) => {
  const [books, setBooks] = useState<Book[]>([]);
  const [error, setError] = useState('');

  useEffect(() => {
    const load = async () => {
      try {
        await refreshToken();

        if (token) {
          const response = await fetch('http://localhost:3001/books', {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          });

          if (response.ok) {
            setBooks(await response.json());
          } else {
            throw new Error();
          }
        }
      } catch {
        setError('Es ist ein Fehler aufgetreten');
      }
    };

    load();
  }, [token]);

  if (error) {
    return <div>{error}</div>;
  }

  return (
    <div>
      <ul>
        {books.map((book) => (
          <li key={book.id}>{book.title}</li>
        ))}
      </ul>
    </div>
  );
};

export default BooksList;
