import { useNavigate } from 'react-router';
import { useAppDispatch, useAppSelector } from '../../app/hooks';
import {
  loadData,
  remove,
  selectAllBooks,
  selectRemoveStatus,
  selectStatus,
} from './booksSlice';
import { useEffect } from 'react';

const List: React.FC = () => {
  const books = useAppSelector(selectAllBooks);
  const loadingStatus = useAppSelector(selectStatus);
  const removeStatus = useAppSelector(selectRemoveStatus);
  const dispatch = useAppDispatch();
  const navigate = useNavigate();

  useEffect(() => {
    dispatch(loadData());
  }, []);

  if (loadingStatus === 'loading') {
    return <div>Lade Bücher...</div>;
  } else if (loadingStatus === 'failed') {
    return <div>Fehler beim Laden der Bücher.</div>;
  }

  return (
    <>
      {removeStatus === 'loading' && <div>Datensatz wird gelöscht</div>}
      {removeStatus === 'failed' && (
        <div>Beim Löschen ist ein Fehler aufgetreten</div>
      )}

      <table>
        <thead>
          <tr>
            <td>Titel</td>
            <td>Autor</td>
            <td>ISBN</td>
            <th></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={() => dispatch(remove(book.id))}>
                  Entfernen
                </button>
              </td>
              <td>
                <button onClick={() => navigate(`/edit/${book.id}`)}>
                  Bearbeiten
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
      <button onClick={() => navigate('/new')}>Buch hinzufügen</button>
    </>
  );
};

export default List;
