import { useMemo, useState } from 'react'
import { usePromotions } from '../context/PromotionsContext.jsx'

export default function PromotionsPage() {
  const { promotions, createPromotion, removePromotion, setPromotionActive } =
    usePromotions()

  const [code, setCode] = useState('')
  const [value, setValue] = useState(10)
  const [notice, setNotice] = useState(null)
  const [error, setError] = useState(null)

  const sorted = useMemo(() => {
    return [...promotions].sort((a, b) => {
      if (a.active !== b.active) return a.active ? -1 : 1
      return String(a.code).localeCompare(String(b.code))
    })
  }, [promotions])

  function handleSubmit(e) {
    e.preventDefault()
    setError(null)
    setNotice(null)
    try {
      createPromotion({ code, value })
      setNotice('Promotion créée.')
      setCode('')
      setValue(10)
    } catch (err) {
      setError(err?.message || 'Impossible de créer la promotion.')
    }
  }

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

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

      <div className="promo-grid">
        <section className="order-panel">
          <h3 className="panel-title">Créer une promotion</h3>
          <form className="promo-form" onSubmit={handleSubmit}>
            <label>
              Code
              <input
                value={code}
                onChange={(e) => setCode(e.target.value)}
                placeholder="Ex. BUT10"
              />
            </label>
            <label>
              Remise (%)
              <input
                type="number"
                min={1}
                max={90}
                value={value}
                onChange={(e) => setValue(Number(e.target.value) || 0)}
              />
            </label>
            <button type="submit" className="btn primary">
              Créer (POST)
            </button>
          </form>
          <p className="promo-hint">
            Astuce : le code est normalisé (majuscules, sans espaces).
          </p>
        </section>

        <section className="order-panel">
          <h3 className="panel-title">Promotions existantes</h3>
          {sorted.length === 0 ? (
            <p className="empty-state">Aucune promotion créée.</p>
          ) : (
            <ul className="promo-list">
              {sorted.map((p) => (
                <li key={p.id} className="promo-item">
                  <div className="promo-item-main">
                    <div>
                      <p className="promo-code">{p.code}</p>
                      <p className="promo-meta">−{p.value}%</p>
                    </div>
                    <div className="promo-actions">
                      <button
                        type="button"
                        className="btn small"
                        onClick={() => setPromotionActive(p.code, !p.active)}
                      >
                        {p.active ? 'Désactiver' : 'Activer'}
                      </button>
                      <button
                        type="button"
                        className="btn small danger"
                        onClick={() => removePromotion(p.code)}
                      >
                        Supprimer
                      </button>
                    </div>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </section>
      </div>
    </div>
  )
}

