import type { ReactNode } from 'react';
import { deleteBook, getAllBooks } from './books.api';
import {
  useMutation,
  useQueryClient,
  useSuspenseQuery,
} from '@tanstack/react-query';

const BooksList: React.FC = () => {
  const queryClient = useQueryClient();

  const { data: books } = useSuspenseQuery({
    queryKey: ['books'],
    queryFn: getAllBooks,
  });

  const deleteMutation = useMutation({
    mutationFn: deleteBook,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['books'] });
    },
  });

  let mutationState: ReactNode = '';
  if (deleteMutation.isPending) {
    mutationState = <div>Löschen...</div>;
  } else if (deleteMutation.isError) {
    mutationState = <div>Fehler beim Löschen</div>;
  }

  if (books.length === 0) {
    return (
      <>
        {mutationState}
        <div>Keine Bücher gefunden</div>
      </>
    );
  } else {
    return (
      <>
        {mutationState}
        <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={() => deleteMutation.mutate(book.id)}>
                    Löschen
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </>
    );
  }
};

export default BooksList;
