import { useBooksContext } from './BooksContext';
import { StarBorder, Star } from '@mui/icons-material';
import type { Book } from './Book';

type Props = {
  book: Book;
};

const BooksListItem: React.FC<Props> = ({ book }) => {
  const [, setBooks] = useBooksContext();

  function handleRate(id: number, rating: number): void {
    setBooks((prevState) => {
      const clone = structuredClone(prevState);
      return clone.map((book) => {
        if (book.id === id) {
          return { ...book, rating };
        }
        return book;
      });
    });
  }

  return (
    <tr>
      <td>{book.title}</td>
      <td>{book.author ? book.author : 'Unbekannt'}</td>
      <td>{book.isbn}</td>
      <td>
        {new Array(5).fill('').map((_, i) => (
          <button
            className="ratingButton"
            key={i}
            onClick={() => handleRate(book.id, i + 1)}
          >
            {book.rating < i + 1 ? <StarBorder /> : <Star />}
          </button>
        ))}
      </td>
    </tr>
  );
};

export default BooksListItem;
