// Convertit une saisie en euros (string "xx.xx" ou "xx,xx") vers des centimes (entier)
function parsePriceToCents(input) {
  let s = String(input ?? '').trim();
  if (!s) return NaN;
  s = s.replace(',', '.');
  const num = Number.parseFloat(s);
  if (Number.isNaN(num)) return NaN;
  return Math.round(num * 100);
}

function AdminCustomPrices() {
  const { user } = window.AuthContext.useAuth();
  const toast = window.Toast.useToast();
  // Valeurs éditables en euros (strings), par catégorie
  const [prices, setPrices] = React.useState({}); // { [category]: '12.34' }
  const [newCat, setNewCat] = React.useState('');
  const [newPrice, setNewPrice] = React.useState(''); // euros string

  React.useEffect(() => {
    (async () => {
      try {
        const res = await window.CustomPricesAPI.getAll();
        const centsMap = res.prices || {};
        // Conversion centimes -> euros (string à 2 décimales) pour l'affichage dans les inputs
        const eurosMap = Object.fromEntries(
          Object.entries(centsMap).map(([cat, cents]) => [cat, (Number(cents) / 100).toFixed(2)])
        );
        setPrices(eurosMap);
      } catch (e) {
        toast.error('Erreur chargement des tarifs');
      }
    })();
  }, []);

  async function save(cat, priceEuros) {
    try {
      const cents = parsePriceToCents(priceEuros);
      if (!Number.isFinite(cents)) {
        toast.error('Prix invalide. Utilisez le format 11.11');
        return;
      }
      // Création/Mise à jour d'un tarif pour une catégorie
      await window.CustomPricesAPI.set(cat, cents);
      setPrices(p => ({ ...p, [cat]: (cents / 100).toFixed(2) }));
      toast.success('Tarif enregistré');
    } catch (e) { toast.error('Erreur enregistrement'); }
  }

  async function remove(cat) {
    try {
      // Suppression du tarif spécifique (retour au prix par défaut côté serveur)
      await window.CustomPricesAPI.remove(cat);
      setPrices(({ [cat]: _, ...rest }) => rest);
      toast.success('Tarif supprimé (retour au défaut)');
    } catch (e) { toast.error('Erreur suppression'); }
  }

  if (!user || user.role !== 'admin') return <p>Accès réservé aux administrateurs.</p>;

  const entries = Object.entries(prices).sort((a,b)=>a[0].localeCompare(b[0]));

  return (
    <div className="container">
      <h1>Tarifs des commandes personnalisées</h1>
      <table style={{ width:'100%', maxWidth: 700, borderCollapse:'collapse' }}>
        <thead><tr><th align="left">Catégorie</th><th align="right">Prix (€)</th><th></th></tr></thead>
        <tbody>
          {entries.map(([cat, price]) => (
            <tr key={cat}>
              <td>{cat}</td>
              <td align="right">
                {/* Edition du prix en euros (format xx.xx) */}
                <input type="number" min="0" step="0.01" placeholder="11.11" value={price} onChange={(e)=>setPrices(p=>({ ...p, [cat]: e.target.value }))} style={{ width:120 }} />
              </td>
              <td align="right">
                <button onClick={()=>save(cat, prices[cat])}>Enregistrer</button>
                <button style={{ marginLeft: 6 }} onClick={()=>remove(cat)}>Supprimer</button>
              </td>
            </tr>
          ))}
          <tr>
            <td>
              {/* Ajout d'une nouvelle catégorie */}
              <input placeholder="Nouvelle catégorie" value={newCat} onChange={(e)=>setNewCat(e.target.value)} />
            </td>
            <td align="right">
              <input type="number" min="0" step="0.01" placeholder="11.11" value={newPrice} onChange={(e)=>setNewPrice(e.target.value)} style={{ width:120 }} />
            </td>
            <td align="right">
              {/* Ajoute puis réinitialise les champs */}
              <button onClick={()=>{ if(!newCat.trim()) return; save(newCat.trim(), newPrice); setNewCat(''); setNewPrice(''); }}>Ajouter</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

window.Pages = window.Pages || {};
window.Pages.AdminCustomPrices = AdminCustomPrices;
