import { useEffect, useState, type ComponentType } from 'react';
import type { Book } from './Book';

type Props = {
  books: Book[];
  error: string | null;
};

function withBooks<P extends Props>(Component: ComponentType<P>) {
  return function WithBooks(props: Omit<P, 'books' | 'error'>) {
    const [books, setBooks] = useState<Book[]>([]);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
      (async () => {
        try {
          const response = await fetch(
            `${import.meta.env.VITE_API_SERVER}/books`
          );
          if (!response.ok) {
            throw new Error('Anfrage fehlgeschlagen');
          }
          const data = await response.json();
          setBooks(data);
        } catch (error) {
          console.error(error);
          setError('Es ist ein Fehler aufgetreten');
        }
      })();
    }, []);
    return <Component {...(props as P)} books={books} error={error} />;
  };
}

export default withBooks;
