/* Restock — recommandations de réapprovisionnement
   GET  /api/restock-recommendations (cached)
   POST /api/restock-recommendations (force recalc)
   Item shape: { asin, name, stock, velocityPerDay, daysOfStock, urgency,
                 reorderQty, reorderByDate, leadTime, supplier?, unitCost? } */

const URG_TONE = { critical: "red", warning: "amber", ok: "green" };
const URG_LABEL = { critical: "Urgent", warning: "Attention", ok: "OK" };

const fmtNum = (n, d = 0) => Number(n || 0).toLocaleString("fr-CA", {
  minimumFractionDigits: d, maximumFractionDigits: d,
});

const Restock = ({ onNavigate }) => {
  const toast = (window.useToast || (() => () => {}))();
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [recalc, setRecalc] = useState(false);
  const [filter, setFilter] = useState("all");
  const [err, setErr] = useState(null);

  const load = async (force = false) => {
    if (force) setRecalc(true); else setLoading(true);
    setErr(null);
    try {
      const r = await fetch("/api/restock-recommendations" + (force ? "" : "?_t=" + Date.now()), {
        method: force ? "POST" : "GET",
      });
      const d = await r.json();
      if (!r.ok || d.error) {
        setErr(d.error || `HTTP ${r.status}`);
        toast?.({ message: "Erreur restock: " + (d.error || r.status), tone: "red" });
      } else {
        setData(d);
        if (force) toast?.({ message: "Recalcul terminé", tone: "green" });
      }
    } catch (e) {
      setErr(e.message);
      toast?.({ message: "Erreur réseau: " + e.message, tone: "red" });
    } finally {
      setLoading(false); setRecalc(false);
    }
  };

  useEffect(() => { load(false); }, []);

  const items = (data && Array.isArray(data.items)) ? data.items : [];
  const counts = data?.counts || {
    critical: items.filter(i => i.urgency === "critical").length,
    warning: items.filter(i => i.urgency === "warning").length,
    ok: items.filter(i => i.urgency === "ok").length,
  };

  const visible = filter === "all"
    ? items
    : items.filter(i => i.urgency === filter);

  // Tri: urgent d'abord, puis days-of-stock croissants
  const sorted = [...visible].sort((a, b) => {
    const ord = { critical: 0, warning: 1, ok: 2 };
    if (ord[a.urgency] !== ord[b.urgency]) return ord[a.urgency] - ord[b.urgency];
    return (a.daysOfStock || 999) - (b.daysOfStock || 999);
  });

  const orderMailto = (item) => {
    // Tente de trouver le fournisseur lié à ce produit
    const supplierId = item.supplier || item.supplierId;
    let supplierEmail = null;
    if (supplierId && Array.isArray(window.SUPPLIERS)) {
      const sup = window.SUPPLIERS.find(s => s.id === supplierId || s.name === supplierId);
      if (sup) supplierEmail = sup.email || sup.contactEmail;
    }
    const subject = `Réapprovisionnement — ${item.name || item.asin} — Qté ${item.reorderQty}`;
    const body = `Bonjour,

Nous souhaitons placer une commande de réapprovisionnement pour le produit suivant:

• Produit: ${item.name || item.asin}
• ASIN: ${item.asin}
• Quantité: ${fmtNum(item.reorderQty)} unités
• Date de commande limite: ${item.reorderByDate}
• Couverture cible: 30 jours

Pourriez-vous confirmer:
- Disponibilité de stock
- Prix unitaire et MOQ
- Délai de production/livraison
- Termes de paiement (Net 30/45 préféré)

Merci d'avance,

Clarens Benoit
Co-fondateur, KCC Holdings
benoitclarens123@gmail.com`;

    if (supplierEmail) {
      window.location.href = `mailto:${encodeURIComponent(supplierEmail)}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
    } else {
      try {
        navigator.clipboard.writeText(`SUJET: ${subject}\n\n${body}`);
        toast?.({ message: "Aucun email fournisseur — modèle copié", tone: "amber" });
      } catch (_) {
        toast?.({ message: "Aucun email fournisseur lié à ce produit", tone: "amber" });
      }
    }
  };

  const exportCsv = () => {
    if (!sorted.length) return;
    const headers = ["asin", "name", "supplier", "stock", "velocity_per_day", "days_of_stock", "urgency", "reorder_qty", "reorder_by", "lead_time"];
    const rows = sorted.map(i => [
      i.asin || "",
      `"${(i.name || "").replace(/"/g, '""')}"`,
      i.supplier || "",
      fmtNum(i.stock),
      fmtNum(i.velocityPerDay, 2),
      fmtNum(i.daysOfStock, 1),
      i.urgency,
      fmtNum(i.reorderQty),
      i.reorderByDate || "",
      fmtNum(i.leadTime),
    ].join(","));
    const csv = [headers.join(","), ...rows].join("\n");
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url; a.download = `restock-${new Date().toISOString().slice(0,10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
    toast?.({ message: "CSV exporté", tone: "green" });
  };

  return (
    <div className="page" style={{ maxWidth: 1280 }}>
      <div className="page-head">
        <div>
          <div className="page-title">Restock</div>
          <div className="page-sub">
            {counts.critical || 0} urgent{(counts.critical || 0) > 1 ? "s" : ""} ·
            {" "}{counts.warning || 0} attention ·
            {" "}{counts.ok || 0} OK
            {data?.cached && " · cache"}
          </div>
        </div>
        <div className="row" style={{ gap: 6 }}>
          <button className="btn" onClick={exportCsv} disabled={!sorted.length}>
            <Icon name="download" size={12}/> CSV
          </button>
          <button className="btn" onClick={() => load(false)} disabled={loading}>
            <Icon name="refresh" size={12}/> {loading ? "…" : "Recharger"}
          </button>
          <button className="btn" data-variant="primary" onClick={() => load(true)} disabled={recalc}>
            <Icon name="sparkles" size={12}/> {recalc ? "Calcul…" : "Recalculer"}
          </button>
        </div>
      </div>

      <div className="row" style={{ gap: 6, marginBottom: 12, flexWrap: "wrap" }}>
        <button className="btn" data-variant={filter === "all" ? "primary" : "ghost"} onClick={() => setFilter("all")}>
          Tous · {items.length}
        </button>
        <button className="btn" data-variant={filter === "critical" ? "primary" : "ghost"} onClick={() => setFilter("critical")}>
          <Badge tone="red" dot /> Urgent · {counts.critical || 0}
        </button>
        <button className="btn" data-variant={filter === "warning" ? "primary" : "ghost"} onClick={() => setFilter("warning")}>
          <Badge tone="amber" dot /> Attention · {counts.warning || 0}
        </button>
        <button className="btn" data-variant={filter === "ok" ? "primary" : "ghost"} onClick={() => setFilter("ok")}>
          <Badge tone="green" dot /> OK · {counts.ok || 0}
        </button>
      </div>

      {err && (
        <div className="card" style={{ padding: 14, marginBottom: 12, background: "color-mix(in srgb, var(--red) 12%, transparent)", border: "1px solid var(--red)" }}>
          <div style={{ fontSize: 12.5, fontWeight: 600, color: "var(--red)" }}>Erreur API</div>
          <div className="mono" style={{ fontSize: 11.5, marginTop: 4 }}>{err}</div>
          <div style={{ fontSize: 11.5, marginTop: 6, color: "var(--text-dim)" }}>
            Vérifie que les produits ont <code>stock</code> et <code>velocity7d</code> (ou <code>monthlySales</code>) en D1.
          </div>
        </div>
      )}

      {loading && !data && (
        <div className="card" style={{ padding: 30, textAlign: "center", color: "var(--text-faint)" }}>
          Chargement…
        </div>
      )}

      {!loading && sorted.length === 0 && !err && (
        <div className="card" style={{ padding: 30, textAlign: "center", color: "var(--text-faint)" }}>
          Aucune recommandation. Lance « Recalculer » ou importe des produits avec stock + velocity.
        </div>
      )}

      {sorted.length > 0 && (
        <div className="card" style={{ padding: 0, overflow: "hidden" }}>
          <table className="table" style={{ fontSize: 12.5 }}>
            <thead>
              <tr>
                <th style={{ width: 100 }}>ASIN</th>
                <th>Produit</th>
                <th style={{ textAlign: "right" }}>Stock</th>
                <th style={{ textAlign: "right" }}>Vente/jour</th>
                <th style={{ textAlign: "right" }}>Jours stock</th>
                <th>Urgence</th>
                <th style={{ textAlign: "right" }}>Qté à commander</th>
                <th>Date limite</th>
                <th>Fournisseur</th>
                <th style={{ width: 110 }}></th>
              </tr>
            </thead>
            <tbody>
              {sorted.map(i => (
                <tr key={i.asin || i.id}>
                  <td className="mono" style={{ fontSize: 11 }}>{i.asin}</td>
                  <td style={{ maxWidth: 280, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{i.name || "—"}</td>
                  <td className="mono" style={{ textAlign: "right" }}>{fmtNum(i.stock)}</td>
                  <td className="mono" style={{ textAlign: "right" }}>{fmtNum(i.velocityPerDay, 2)}</td>
                  <td className="mono" style={{ textAlign: "right", fontWeight: i.urgency === "critical" ? 600 : 400, color: i.urgency === "critical" ? "var(--red)" : i.urgency === "warning" ? "var(--amber)" : "inherit" }}>
                    {fmtNum(i.daysOfStock, 1)}
                  </td>
                  <td>
                    <Badge tone={URG_TONE[i.urgency]} dot>{URG_LABEL[i.urgency] || i.urgency}</Badge>
                  </td>
                  <td className="mono" style={{ textAlign: "right", fontWeight: 600 }}>{fmtNum(i.reorderQty)}</td>
                  <td className="mono" style={{ fontSize: 11 }}>{i.reorderByDate || "—"}</td>
                  <td style={{ fontSize: 11.5 }}>{i.supplier || "—"}</td>
                  <td>
                    <button className="btn" data-variant="primary" data-size="sm" onClick={() => orderMailto(i)}>
                      <Icon name="mail" size={11}/> Commander
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      <div className="muted" style={{ fontSize: 11, marginTop: 12, textAlign: "center" }}>
        Hypothèses : lead time 14j · couverture cible 30j · cron quotidien 11h UTC
      </div>
    </div>
  );
};

window.Restock = Restock;
