import { z } from 'zod';
import Rating from './Rating';

const BookSchema = z.object({
  id: z.number(),
  title: z.string(),
  author: z.string().optional(),
  isbn: z.string(),
  rating: z.number().optional(),
});

const BooksListItemSchema = z.object({
  book: BookSchema,
  onRate: z.function(),
});

function BooksListItem(props) {
  const result = BooksListItemSchema.safeParse(props);

  if (!result.success) {
    console.error('Invalid book prop:', result.error);
    return null;
  }

  const validBook = result.data.book;

  function handleRate(event) {
    const rating = event.target.closest('[data-value]')?.dataset.value;
    if (rating) {
      result.data.onRate(validBook.id, parseInt(rating, 10));
    }
  }

  return (
    <tr>
      <td>{validBook.title}</td>
      <td>{validBook.author ? validBook.author : 'Unbekannt'}</td>
      <td>{validBook.isbn}</td>
      <td onClick={handleRate}>
        <Rating item={validBook} />
      </td>
    </tr>
  );
}

export default BooksListItem;
