import { useCallback, useState } from 'react';

type Book = {
  id: number;
  title: string;
  rating: number;
};

const initialBooks: Book[] = [
  { id: 1, title: 'JavaScript - das umfassende Handbuch', rating: 5 },
  { id: 2, title: 'Clean Code', rating: 4 },
  { id: 3, title: 'Design Patterns', rating: 5 },
];

const BooksList: React.FC = () => {
  const [books, setBooks] = useState<Book[]>(initialBooks);

  const rateBook = useCallback((id: number, rating: number) => {
    setBooks((prevBooks) =>
      prevBooks.map((book) => (book.id === id ? { ...book, rating } : book))
    );
  }, []);

  return (
    <table>
      <thead>
        <tr>
          <th>Titel</th>
          <th>Bewertung</th>
        </tr>
      </thead>
      <tbody>
        {books.map((book) => (
          <BooksListItem key={book.id} book={book} onRate={rateBook} />
        ))}
      </tbody>
    </table>
  );
};

const BooksListItem: React.FC<{
  book: Book;
  onRate: (id: number, rating: number) => void;
}> = ({ book, onRate }) => {
  const handleRate = useCallback(
    (rating: number) => {
      onRate(book.id, rating);
    },
    [book.id, onRate]
  );

  console.log('Render:', book.title);

  return (
    <tr>
      <td>{book.title}</td>
      <td>
        {new Array(5).fill('').map((_, i) => (
          <button key={i} onClick={() => handleRate(i + 1)}>
            {i < book.rating ? '\u2605' : '\u2606'}
          </button>
        ))}
      </td>
    </tr>
  );
};

export default BooksList;
