import { useMemo, useState } from 'react'
import { useBooks } from '../context/BooksContext.jsx'
import { useOrders } from '../context/OrdersContext.jsx'
import { usePromotions } from '../context/PromotionsContext.jsx'

function formatEUR(amount) {
  const n = Number(amount) || 0
  return new Intl.NumberFormat('fr-FR', {
    style: 'currency',
    currency: 'EUR',
    maximumFractionDigits: 2,
  }).format(n)
}

function toQtyMap(items) {
  const map = new Map()
  for (const it of items) map.set(it.bookId, it.qty)
  return map
}

export default function CommandePage() {
  const { books } = useBooks()
  const { createOrder } = useOrders()
  const { getActivePromotionByCode, normalizeCode } = usePromotions()

  const [qtyByBookId, setQtyByBookId] = useState(() => ({}))
  const [promoInput, setPromoInput] = useState('')
  const [notice, setNotice] = useState(null)
  const [error, setError] = useState(null)

  const items = useMemo(() => {
    return books
      .map((b) => {
        const qty = Math.max(0, Math.trunc(Number(qtyByBookId[b.id]) || 0))
        const unitPrice = Number(b.price)
        return {
          bookId: b.id,
          title: b.title,
          unitPrice: Number.isFinite(unitPrice) ? unitPrice : 10,
          qty,
        }
      })
      .filter((it) => it.qty > 0)
  }, [books, qtyByBookId])

  const subtotal = useMemo(() => {
    return items.reduce((sum, it) => sum + it.unitPrice * it.qty, 0)
  }, [items])

  const promo = useMemo(() => {
    const code = normalizeCode(promoInput)
    if (!code) return null
    return getActivePromotionByCode(code)
  }, [promoInput, getActivePromotionByCode, normalizeCode])

  const discount = useMemo(() => {
    if (!promo) return 0
    return (subtotal * promo.value) / 100
  }, [promo, subtotal])

  const total = useMemo(() => Math.max(0, subtotal - discount), [subtotal, discount])

  function setQty(bookId, nextQty) {
    setQtyByBookId((prev) => ({ ...prev, [bookId]: nextQty }))
  }

  function handleSubmit() {
    setError(null)
    setNotice(null)
    try {
      const order = createOrder({
        items,
        promotion: promo ? { code: promo.code, type: promo.type, value: promo.value } : null,
      })
      setQtyByBookId({})
      setPromoInput('')
      const map = toQtyMap(order.items)
      setNotice(
        `Commande ${order.id.slice(0, 8)} créée (${map.size} livre${
          map.size > 1 ? 's' : ''
        }). Total: ${formatEUR(order.total)}.`,
      )
    } catch (e) {
      setError(e?.message || 'Impossible de créer la commande.')
    }
  }

  return (
    <div className="commande-page">
      <h2 className="page-title">Passer une commande</h2>
      <p className="page-lead">
        Équivalent local de <code>POST /api/orders</code> (aucun backend).
      </p>

      {error ? (
        <p className="form-error" role="alert">
          {error}
        </p>
      ) : null}
      {notice ? <p className="form-notice">{notice}</p> : null}

      {books.length === 0 ? (
        <p className="empty-state">
          Aucun livre dans le catalogue. Ajoute un livre dans “Mes livres” d’abord.
        </p>
      ) : (
        <div className="order-grid">
          <section className="order-panel">
            <h3 className="panel-title">Catalogue</h3>
            <ul className="order-catalog">
              {books.map((b) => (
                <li key={b.id} className="order-catalog-item">
                  <div className="order-catalog-main">
                    <div>
                      <p className="order-book-title">{b.title}</p>
                      <p className="order-book-meta">
                        {b.author} · {formatEUR(b.price ?? 10)}
                      </p>
                    </div>
                    <label className="qty">
                      <span className="qty-label">Qté</span>
                      <input
                        type="number"
                        min={0}
                        step={1}
                        value={qtyByBookId[b.id] ?? 0}
                        onChange={(e) => setQty(b.id, e.target.value)}
                        aria-label={`Quantité pour ${b.title}`}
                      />
                    </label>
                  </div>
                </li>
              ))}
            </ul>
          </section>

          <aside className="order-panel">
            <h3 className="panel-title">Récapitulatif</h3>
            {items.length === 0 ? (
              <p className="empty-state">Sélectionne au moins un livre (quantité &gt; 0).</p>
            ) : (
              <ul className="order-summary">
                {items.map((it) => (
                  <li key={it.bookId} className="order-summary-item">
                    <span>
                      {it.title} × {it.qty}
                    </span>
                    <span>{formatEUR(it.unitPrice * it.qty)}</span>
                  </li>
                ))}
              </ul>
            )}

            <div className="promo-box">
              <label className="promo-label">
                Code promo
                <input
                  className="promo-input"
                  placeholder="Ex. BUT10"
                  value={promoInput}
                  onChange={(e) => setPromoInput(e.target.value)}
                />
              </label>
              <p className="promo-hint">
                Équivalent local de <code>POST /api/promotions</code> (créées dans “Promotions”).
              </p>
              {promoInput.trim() && !promo ? (
                <p className="promo-warn">Code invalide ou inactif.</p>
              ) : null}
              {promo ? (
                <p className="promo-ok">
                  Promo appliquée : <strong>{promo.code}</strong> (−{promo.value}%)
                </p>
              ) : null}
            </div>

            <div className="totals">
              <div className="totals-row">
                <span>Sous-total</span>
                <span>{formatEUR(subtotal)}</span>
              </div>
              <div className="totals-row">
                <span>Remise</span>
                <span>−{formatEUR(discount)}</span>
              </div>
              <div className="totals-row total">
                <span>Total</span>
                <span>{formatEUR(total)}</span>
              </div>
            </div>

            <button type="button" className="btn primary" onClick={handleSubmit}>
              Passer commande (POST)
            </button>
          </aside>
        </div>
      )}
    </div>
  )
}

