// Admin panel — vista de tienda para la vendedora

const { useState: useStateA, useMemo: useMemoA } = React;

function AdminPanel({ data, onClose, currency, rates, products, setProducts }) {
  const [tab, setTab] = useStateA("dashboard");
  const [showForm, setShowForm] = useStateA(false);
  const [editing, setEditing] = useStateA(null);

  const lowStock = products.filter(p => p.stock > 0 && p.stock < 10).length;
  const outStock = products.filter(p => p.stock === 0).length;

  return (
    <div className="admin-shell">
      <div className="admin-top">
        <div>
          <div className="crumbs">mima edit · ADMIN</div>
          <h1>Tu tienda</h1>
        </div>
        <button onClick={onClose} className="icon-btn" style={{ width: 36, height: 36, borderRadius: "50%", background: "var(--cream-2)", display: "grid", placeItems: "center" }}><I.Close size={16} /></button>
      </div>
      <div className="admin-tabs">
        <button className={"tab" + (tab === "dashboard" ? " active" : "")} onClick={() => setTab("dashboard")}>Resumen</button>
        <button className={"tab" + (tab === "products" ? " active" : "")} onClick={() => setTab("products")}>Productos</button>
        <button className={"tab" + (tab === "import" ? " active" : "")} onClick={() => setTab("import")}>Importar CSV</button>
        <button className={"tab" + (tab === "orders" ? " active" : "")} onClick={() => setTab("orders")}>Pedidos</button>
      </div>

      <div className="admin-body">
        {tab === "dashboard" && (
          <>
            <div className="kpi-row">
              <div className="kpi"><div className="lb">Ventas hoy</div><div className="val">$ 184.500</div><div className="delta">+24% vs. ayer</div></div>
              <div className="kpi"><div className="lb">Pedidos</div><div className="val">12</div><div className="delta">3 pendientes</div></div>
              <div className="kpi"><div className="lb">Productos</div><div className="val">{products.length}</div><div className="delta">{lowStock} con stock bajo</div></div>
              <div className="kpi"><div className="lb">Sin stock</div><div className="val">{outStock}</div><div className="delta down">Reponer</div></div>
            </div>
            <div className="section-head" style={{ marginBottom: 12 }}>
              <h2 style={{ fontSize: 18 }}>Stock que requiere atención</h2>
            </div>
            <div className="admin-table">
              {products.filter(p => p.stock < 15).slice(0, 4).map(p => (
                <div className="admin-row" key={p.id}>
                  <div className="thumb-sm" style={productTones(p)} />
                  <div>
                    <div className="nm">{p.name}</div>
                    <div className="sub">{p.tagline}</div>
                  </div>
                  <span className={"stock-pill " + (p.stock === 0 ? "out" : p.stock < 10 ? "low" : "")}>{p.stock === 0 ? "AGOTADO" : p.stock + " UDS"}</span>
                </div>
              ))}
            </div>
          </>
        )}

        {tab === "products" && (
          <>
            <div style={{ display: "flex", gap: 8, marginBottom: 14 }}>
              <div className="search-bar" style={{ margin: 0, flex: 1 }}>
                <I.Search size={14} />
                <input placeholder="Buscar producto…" />
              </div>
              <button className="btn btn-primary" onClick={() => { setEditing(null); setShowForm(true); }}>
                <I.Plus size={14} /> Nuevo
              </button>
            </div>
            <div className="admin-table">
              {products.map(p => (
                <div className="admin-row" key={p.id} onClick={() => { setEditing(p); setShowForm(true); }} style={{ cursor: "pointer" }}>
                  <div className="thumb-sm" style={productTones(p)} />
                  <div>
                    <div className="nm">{p.name}</div>
                    <div className="sub">{formatPrice(p.price, currency, rates)} · {p.tagline}</div>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                    <span className={"stock-pill " + (p.stock === 0 ? "out" : p.stock < 10 ? "low" : "")}>
                      {p.stock === 0 ? "0" : p.stock} UDS
                    </span>
                    <I.Edit size={14} />
                  </div>
                </div>
              ))}
            </div>
          </>
        )}

        {tab === "import" && (
          <>
            <div className="upload-zone">
              <div className="icon"><I.Upload size={32} /></div>
              <h4>Subí tu CSV o Excel</h4>
              <p>Arrastrá el archivo o tocá para elegirlo. Reconocemos columnas: nombre, categoría, precio, stock, descripción.</p>
              <button className="btn btn-sage">Elegir archivo</button>
            </div>
            <div style={{ background: "var(--paper)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", padding: 14 }}>
              <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-3)", marginBottom: 8 }}>Plantilla recomendada</div>
              <pre style={{ fontFamily: "var(--mono)", fontSize: 11, margin: 0, color: "var(--ink-2)", whiteSpace: "pre-wrap", lineHeight: 1.6 }}>
                {"nombre,categoria,precio_ars,stock,tagline,descripcion\n"}
                {"Eau de Parfum Lirio,perfumeria,48900,23,Floral · 75ml,Una fragancia luminosa…\n"}
                {"Sérum Vit. C,facial,32400,41,Antioxidante · 30ml,Concentración alta de…"}
              </pre>
              <button className="btn btn-ghost btn-sm" style={{ marginTop: 12 }}>Descargar plantilla</button>
            </div>
            <div style={{ marginTop: 16, fontSize: 12, color: "var(--ink-3)" }}>
              💡 Última importación: hace 4 días · 8 productos actualizados
            </div>
          </>
        )}

        {tab === "orders" && (
          <>
            {[
              { id: "AR-2026-0042", buyer: "Camila S.", total: 64500, status: "Pendiente envío", color: "terra" },
              { id: "AR-2026-0041", buyer: "Florencia M.", total: 32400, status: "En preparación", color: "sage" },
              { id: "AR-2026-0040", buyer: "Magdalena R.", total: 89400, status: "Enviado", color: "sage" },
              { id: "AR-2026-0039", buyer: "Lucía D.", total: 18700, status: "Entregado", color: "ink" },
            ].map(o => (
              <div key={o.id} style={{ padding: 14, background: "var(--paper)", border: "1px solid var(--line)", borderRadius: "var(--r-md)", marginBottom: 8, display: "flex", alignItems: "center", gap: 12 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: "var(--mono)", fontSize: 10, letterSpacing: "0.1em", color: "var(--ink-3)", marginBottom: 3 }}>{o.id}</div>
                  <div style={{ fontFamily: "var(--serif)", fontSize: 16 }}>{o.buyer}</div>
                  <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 2 }}>{formatPrice(o.total, currency, rates)}</div>
                </div>
                <span style={{
                  fontSize: 10, fontFamily: "var(--mono)", letterSpacing: "0.06em", padding: "5px 9px", borderRadius: 999,
                  background: o.color === "terra" ? "var(--terra-100)" : o.color === "sage" ? "var(--sage-100)" : "var(--cream-2)",
                  color: o.color === "terra" ? "var(--terra-700)" : o.color === "sage" ? "var(--sage-900)" : "var(--ink-2)",
                }}>{o.status.toUpperCase()}</span>
                <I.ChevR size={14} />
              </div>
            ))}
          </>
        )}
      </div>

      {showForm && <ProductForm product={editing} onClose={() => setShowForm(false)} onSave={(p) => {
        if (editing) {
          setProducts(products.map(x => x.id === p.id ? p : x));
        } else {
          setProducts([...products, { ...p, id: "p" + (products.length + 1).toString().padStart(2, "0") }]);
        }
        setShowForm(false);
      }} cats={data.categories} />}
    </div>
  );
}

function ProductForm({ product, onClose, onSave, cats }) {
  const [f, setF] = useStateA(product || {
    name: "", category: cats[0]?.id || "perfumeria",
    tagline: "", price: 0, stock: 0,
    description: "", notes: [],
    tones: ["#efe4cf", "#c9b58a"],
    isNew: true,
  });
  const [notesText, setNotesText] = useStateA(f.notes.join("\n"));
  const u = (k, v) => setF(s => ({ ...s, [k]: v }));

  const save = () => {
    onSave({ ...f, notes: notesText.split("\n").filter(Boolean), price: Number(f.price), stock: Number(f.stock) });
  };

  return (
    <>
      <div className="sheet-backdrop" onClick={onClose} />
      <div className="sheet" style={{ maxHeight: "92%" }}>
        <div className="handle" />
        <div className="sheet-head">
          <h3>{product ? "Editar producto" : "Nuevo producto"}</h3>
          <button className="close-btn" onClick={onClose}><I.Close size={16} /></button>
        </div>
        <div className="sheet-body" style={{ padding: "10px 22px 20px" }}>
          <div className="field">
            <label>Foto del producto</label>
            <div style={{
              height: 120, borderRadius: "var(--r-md)", border: "2px dashed var(--line)",
              background: `linear-gradient(160deg, ${f.tones[0]}, ${f.tones[1]})`,
              display: "grid", placeItems: "center", color: "var(--cream)", position: "relative", cursor: "pointer"
            }}>
              <div style={{ background: "var(--cream)", color: "var(--ink)", padding: "8px 14px", borderRadius: 999, fontSize: 12 }}>
                <I.Upload size={14} style={{ verticalAlign: "middle", marginRight: 6 }} />
                Subir foto
              </div>
            </div>
          </div>
          <div className="field">
            <label>Nombre</label>
            <input value={f.name} onChange={(e) => u("name", e.target.value)} placeholder="Eau de Parfum Lirio Blanco" />
          </div>
          <div className="field">
            <label>Categoría</label>
            <select value={f.category} onChange={(e) => u("category", e.target.value)}>
              {cats.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
            </select>
          </div>
          <div className="field">
            <label>Subtítulo (ml, tipo)</label>
            <input value={f.tagline} onChange={(e) => u("tagline", e.target.value)} placeholder="Floral · 75ml" />
          </div>
          <div className="field-row">
            <div className="field">
              <label>Precio ARS</label>
              <input type="number" value={f.price} onChange={(e) => u("price", e.target.value)} />
            </div>
            <div className="field">
              <label>Stock</label>
              <input type="number" value={f.stock} onChange={(e) => u("stock", e.target.value)} />
            </div>
          </div>
          <div className="field">
            <label>Descripción</label>
            <textarea rows="3" value={f.description} onChange={(e) => u("description", e.target.value)} placeholder="Una fragancia luminosa…" />
          </div>
          <div className="field">
            <label>Notas / activos (uno por línea)</label>
            <textarea rows="3" value={notesText} onChange={(e) => setNotesText(e.target.value)} placeholder="Lirio del valle&#10;Bergamota&#10;Almizcle blanco" />
          </div>
          <div className="field">
            <label>Tonos del envase (gradiente)</label>
            <div style={{ display: "flex", gap: 10 }}>
              <input type="color" value={f.tones[0]} onChange={(e) => u("tones", [e.target.value, f.tones[1]])} style={{ width: 60, height: 44, padding: 0, border: "1px solid var(--line)", borderRadius: 10 }} />
              <input type="color" value={f.tones[1]} onChange={(e) => u("tones", [f.tones[0], e.target.value])} style={{ width: 60, height: 44, padding: 0, border: "1px solid var(--line)", borderRadius: 10 }} />
              <div style={{ flex: 1, borderRadius: "var(--r-md)", background: `linear-gradient(160deg, ${f.tones[0]}, ${f.tones[1]})` }} />
            </div>
          </div>
        </div>
        <div className="sheet-foot" style={{ display: "flex", gap: 10 }}>
          <button className="btn btn-ghost" onClick={onClose} style={{ flex: 1 }}>Cancelar</button>
          <button className="btn btn-primary" onClick={save} style={{ flex: 2 }}>{product ? "Guardar cambios" : "Crear producto"}</button>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { AdminPanel });
