import {
  useMutation,
  useReactiveVar,
  useSuspenseQuery,
} from '@apollo/client/react';
import { deleteBooksMutation, getBooksQuery } from './list.graphql';
import type { Book } from './Book';
import { selectedBook } from './apolloClient';

const List: React.FC = () => {
  const { data } = useSuspenseQuery<{ book: Book[] }>(getBooksQuery);
  const [deleteBook] = useMutation(deleteBooksMutation, {
    refetchQueries: ['BooksList'],
  });

  const selectedBookVar = useReactiveVar(selectedBook);

  const handleSelect = (book: Book) => {
    selectedBook(book);
  };

  return (
    <table style={{ borderCollapse: 'collapse' }}>
      <thead>
        <tr>
          <th>Titel</th>
          <th>ISBN</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        {data?.book.map((book) => {
          const isSelected = selectedBookVar?.id === book.id;

          return (
            <tr
              key={book.id}
              onClick={() => handleSelect(book)}
              style={{
                backgroundColor: isSelected ? 'lightgrey' : 'transparent',
                cursor: 'pointer',
              }}
            >
              <td>{book.title}</td>
              <td>{book.isbn}</td>
              <td>
                <button
                  onClick={(e) => {
                    e.stopPropagation();
                    deleteBook({ variables: { id: book.id } });
                  }}
                >
                  löschen
                </button>
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
};

export default List;
