import { useReducer } from 'react';
import { type Book } from './Book';

type Action = { type: 'RATE'; payload: { id: number; rating: number } };

function reducer(state: Book[], action: Action) {
  switch (action.type) {
    case 'RATE':
      return state.map((book) =>
        book.id === action.payload.id
          ? { ...book, rating: action.payload.rating }
          : book
      );
    default:
      return state;
  }
}

const initialBooks: Book[] = [
  {
    id: 1,
    title: 'JavaScript - das umfassende Handbuch',
    author: 'Philip Ackermann',
    isbn: '978-3836286299',
    rating: 5,
  },
];

function BooksList() {
  const [books, dispatch] = useReducer(reducer, initialBooks);
  return (
    <table>
      <thead>
        <tr>
          <th>Titel</th>
          <th>Autor</th>
          <th>ISBN</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>
              {new Array(5).fill('').map((_, i) => (
                <button
                  className="ratingButton"
                  key={i}
                  onClick={() =>
                    dispatch({
                      type: 'RATE',
                      payload: { id: book.id, rating: i + 1 },
                    })
                  }
                >
                  {book.rating < i + 1 ? '\u2606' : '\u2605'}
                </button>
              ))}
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

export default BooksList;
