import { useState } from 'react';
import { useReturns } from '../context/ReturnContext';
import { getBooks } from '../api/books';
import { useEffect } from 'react';

export default function Returns() {
  const { returns, addReturn } = useReturns();
  const [books, setBooks] = useState([]);
  const [form, setForm] = useState({ bookId: '', customerPhone: '', reason: '' });
  const [message, setMessage] = useState(null);

  useEffect(() => {
    getBooks(0, 100).then(res => setBooks(res.data.content)).catch(console.error);
  }, []);

  function handleChange(e) {
    const { name, value } = e.target;
    setForm(f => ({ ...f, [name]: value }));
  }

  function handleSubmit(e) {
    e.preventDefault();
    const book = books.find(b => String(b.isbn) === String(form.bookId));
    const bookTitle = book ? book.title : form.bookId;
    addReturn(form.bookId, bookTitle, form.customerPhone, form.reason);
    setMessage({ success: true, text: 'Retour enregistré avec succès !' });
    setForm({ bookId: '', customerPhone: '', reason: '' });
  }

  return (
    <main>
      <h1>Gestion des retours</h1>

      <section>
        <h2>Enregistrer un retour</h2>
        <form onSubmit={handleSubmit}>
          <label>
            Livre :
            <select name="bookId" value={form.bookId} onChange={handleChange} required>
              <option value="">-- Choisir un livre --</option>
              {books.map(b => (
                <option key={b.isbn} value={b.isbn}>{b.title} — {b.author}</option>
              ))}
            </select>
          </label>
          <label>
            Téléphone du client :
            <input
              name="customerPhone"
              type="tel"
              value={form.customerPhone}
              onChange={handleChange}
              placeholder="0612345678"
              required
            />
          </label>
          <label>
            Motif :
            <textarea
              name="reason"
              value={form.reason}
              onChange={handleChange}
              placeholder="Motif du retour..."
              required
            />
          </label>
          <button type="submit">Enregistrer le retour</button>
        </form>
        {message && <p style={{ color: message.success ? 'green' : 'red' }}>{message.text}</p>}
      </section>

      <section>
        <h2>Historique des retours</h2>
        {returns.length === 0 ? (
          <p>Aucun retour enregistré.</p>
        ) : (
          <ul>
            {returns.map(r => (
              <li key={r.returnId}>
                <strong>{r.bookTitle}</strong>
                <br />
                Client : {r.customerPhone}
                <br />
                Motif : {r.reason}
                <br />
                Statut : {r.status}
                <br />
                <small>{new Date(r.returnedAt).toLocaleDateString('fr-FR')}</small>
              </li>
            ))}
          </ul>
        )}
      </section>
    </main>
  );
}
