import { Link, useNavigate, useParams } from 'react-router-dom'
import { useBooks } from '../context/BooksContext.jsx'

export default function BookDetailPage() {
  const { id } = useParams()
  const navigate = useNavigate()
  const { books, toggleRead, removeBook } = useBooks()
  const book = books.find((b) => b.id === id)

  if (!book) {
    return (
      <div className="book-detail">
        <p className="book-detail-missing">Livre introuvable.</p>
        <Link to="/" className="nav-link">
          ← Retour à mes livres
        </Link>
      </div>
    )
  }

  function handleDelete() {
    removeBook(book.id)
    navigate('/')
  }

  return (
    <article className="book-detail">
      <Link to="/" className="nav-link book-detail-back">
        ← Catalogue
      </Link>
      <span className={`badge ${book.read ? 'read' : 'unread'}`}>
        {book.read ? 'Lu' : 'À lire'}
      </span>
      <h2 className="book-detail-title">{book.title}</h2>
      <p className="book-detail-author">{book.author}</p>
      <dl className="book-detail-meta">
        <div>
          <dt>Année</dt>
          <dd>{book.year}</dd>
        </div>
        <div>
          <dt>Prix</dt>
          <dd>{Number(book.price ?? 10).toFixed(2)} €</dd>
        </div>
        {book.genre ? (
          <div>
            <dt>Genre</dt>
            <dd>{book.genre}</dd>
          </div>
        ) : null}
        <div>
          <dt>Identifiant</dt>
          <dd>
            <code>{book.id}</code>
          </dd>
        </div>
      </dl>
      <div className="book-detail-actions">
        <button
          type="button"
          className="btn"
          onClick={() => toggleRead(book.id)}
        >
          {book.read ? 'Marquer non lu' : 'Marquer lu'}
        </button>
        <button type="button" className="btn danger" onClick={handleDelete}>
          Supprimer de mes livres
        </button>
      </div>
    </article>
  )
}
