import { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { getBookById, reserveBook } from '../api/books';
import { useAuth } from '../context/AuthContext';

export default function BookDetail() {
  const { user } = useAuth();
  const { bookId } = useParams();
  const [book, setBook] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [phoneNumber, setPhoneNumber] = useState('');
  const [reservationStatus, setReservationStatus] = useState(null);
  const [reserving, setReserving] = useState(false);

  useEffect(() => { getBookById(bookId).then((response) => setBook(response.data)).catch((err) => { console.error(err); setError('Livre introuvable.'); }).finally(() => setLoading(false)); }, [bookId]);

  function handleReservation(e) {
    e.preventDefault();
    setReserving(true);
    setReservationStatus(null);
    reserveBook(bookId, { phoneNumber })
      .then(() => {
        setReservationStatus({ success: true, message: 'Réservation effectuée avec succès !' });
        setPhoneNumber('');
      })
      .catch((err) => {
        const msg = err.response?.data || 'Erreur lors de la réservation.';
        setReservationStatus({ success: false, message: msg });
      })
      .finally(() => setReserving(false));
  }

  if (loading) return <main><p>Chargement…</p></main>;
  if (error) return <main><p>{error}</p><Link to="/books">← Retour au catalogue</Link></main>;

  return (
    <main>
      <Link to="/books">← Retour au catalogue</Link>
      <h1>{book.title}</h1>
      <p>Auteur : {book.author}</p>
      <p>ISBN : {book.isbn}</p>
      <p>Éditeur : {book.publisher}</p>
      <p>Publié le : {book.publicationDate}</p>
      <p>Prix : {book.price} €</p>
      <p>Stock : {book.quantity}</p>
      <p>Langue : {book.language}</p>
      <p>Catégories : {book.categories?.join(', ')}</p>
      {book.description && <p>{book.description}</p>}

      {user?.role === 'user' && <section>
        <h2>Réserver ce livre</h2>
        <form onSubmit={handleReservation}>
          <label>
            Numéro de téléphone :
            <input
              type="tel"
              value={phoneNumber}
              onChange={(e) => setPhoneNumber(e.target.value)}
              placeholder="0612345678"
              required
            />
          </label>
          <button type="submit" disabled={reserving}>
            {reserving ? 'Réservation…' : 'Réserver'}
          </button>
        </form>
        {reservationStatus && (
          <p style={{ color: reservationStatus.success ? 'green' : 'red' }}>
            {reservationStatus.message}
          </p>
        )}
      </section>}
    </main>
  );
}