// Módulo 8 — Pedidos

function Pedidos() {
  const [filter, setFilter] = React.useState("Todos");
  const [listening, setListening] = React.useState(false);
  const [dictated, setDictated] = React.useState(null);
  const D = window.APP_DATA;

  const filters = ["Todos", "Facturados", "Lanzados", "Retenidos", "En validación"];
  const orders = D.orders.filter(o => {
    if (filter === "Todos") return true;
    if (filter === "Facturados") return o.status === "Facturado";
    if (filter === "Lanzados") return o.status === "Lanzado";
    if (filter === "Retenidos") return o.status.includes("Retenido");
    if (filter === "En validación") return o.status.includes("Validación");
    return true;
  });

  const startDictate = () => {
    setListening(true);
    setDictated(null);
    setTimeout(() => {
      setListening(false);
      setDictated({
        raw: "Genérame un pedido de 100 unidades de Perfect Finish y 50 de Sintex MS-35 para OBRAMAT Rivas",
        client: "OBRAMAT Rivas",
        items: [
          { product: "Perfect Finish", qty: 100, price: 4.20 },
          { product: "Sintex MS-35", qty: 50, price: 5.80 },
        ],
      });
    }, 1800);
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
      <div className="card" style={{ background: "linear-gradient(135deg, var(--accent), oklch(0.55 0.17 35))", color: "#fff", border: "none", textAlign: "center", padding: 30 }}>
        <div style={{ fontSize: 18, fontWeight: 600 }}>Crear Pedido por Voz</div>
        <div style={{ fontSize: 13, opacity: 0.9, marginTop: 4, marginBottom: 18 }}>
          Pulsa el micrófono y di algo como: <i>"Genérame un pedido de 100 unidades de Perfect Finish y 50 de Sintex MS-35 para OBRAMAT"</i>
        </div>
        <button
          onClick={startDictate}
          disabled={listening}
          style={{
            width: 72, height: 72, borderRadius: 999, border: "3px solid #fff",
            background: listening ? "rgba(255,255,255,0.3)" : "rgba(255,255,255,0.15)",
            color: "#fff", cursor: "pointer", display: "grid", placeItems: "center",
            transition: "transform 200ms",
            transform: listening ? "scale(1.1)" : "scale(1)",
            animation: listening ? "micPulse 1s infinite" : "none",
          }}
        >
          <div style={{ width: 28, height: 28 }}><Icon.Mic /></div>
        </button>
        <div style={{ fontSize: 12, marginTop: 10, opacity: 0.85, minHeight: 16 }}>
          {listening ? "Escuchando..." : dictated ? "✓ Pedido capturado" : "Pulsa para iniciar"}
        </div>
        <style>{`@keyframes micPulse { 0%, 100% { box-shadow: 0 0 0 0 rgba(255,255,255,0.6); } 50% { box-shadow: 0 0 0 18px rgba(255,255,255,0); } }`}</style>
      </div>

      {dictated && (
        <div className="card" style={{ animation: "fadeIn 300ms", border: "1px solid var(--accent)" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 12 }}>
            <div>
              <h3 style={{ margin: 0 }}>Revisar pedido dictado</h3>
              <div style={{ fontSize: 12, color: "var(--ink-muted)", marginTop: 4, fontStyle: "italic" }}>"{dictated.raw}"</div>
            </div>
            <div style={{ display: "flex", gap: 6 }}>
              <button className="btn-secondary" onClick={() => setDictated(null)}>Descartar</button>
              <button className="btn">Confirmar y enviar</button>
            </div>
          </div>
          <div style={{ background: "var(--surface-2)", padding: 12, borderRadius: 8 }}>
            <div style={{ fontSize: 12, color: "var(--ink-muted)", marginBottom: 8 }}>CLIENTE</div>
            <div style={{ fontWeight: 600, marginBottom: 12 }}>{dictated.client}</div>
            <table className="table" style={{ fontSize: 12.5 }}>
              <thead><tr><th>Producto</th><th style={{ textAlign: "right" }}>Cantidad</th><th style={{ textAlign: "right" }}>Precio</th><th style={{ textAlign: "right" }}>Total</th></tr></thead>
              <tbody>
                {dictated.items.map((it, i) => (
                  <tr key={i}>
                    <td style={{ fontWeight: 500 }}>{it.product}</td>
                    <td style={{ textAlign: "right" }}>{it.qty}</td>
                    <td style={{ textAlign: "right" }}>{it.price.toFixed(2)} €</td>
                    <td style={{ textAlign: "right", fontWeight: 600 }}>{(it.qty * it.price).toFixed(2)} €</td>
                  </tr>
                ))}
                <tr><td colSpan="3" style={{ textAlign: "right", fontWeight: 600 }}>Total</td><td style={{ textAlign: "right", fontWeight: 600, color: "var(--accent)" }}>{dictated.items.reduce((s, it) => s + it.qty * it.price, 0).toFixed(2)} €</td></tr>
              </tbody>
            </table>
          </div>
        </div>
      )}

      <div className="card" style={{ padding: "14px 20px" }}>
        <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
          {filters.map(f => (
            <button key={f} className={f === filter ? "btn" : "btn-ghost"} style={{ padding: "6px 14px", fontSize: 12.5 }} onClick={() => setFilter(f)}>{f}</button>
          ))}
        </div>
      </div>

      <div className="card" style={{ padding: 0, overflow: "hidden" }}>
        <table className="table">
          <thead><tr><th>N.º Pedido</th><th>Cliente</th><th>Fecha</th><th>Importe</th><th>Estado</th><th>Progreso</th><th></th></tr></thead>
          <tbody>
            {orders.map(o => (
              <tr key={o.id}>
                <td className="mono" style={{ fontWeight: 600 }}>{o.id}</td>
                <td>{o.client}</td>
                <td>{o.date}</td>
                <td style={{ fontWeight: 600 }}>{o.amount}</td>
                <td><OrderStatusBadge s={o.status} /></td>
                <td style={{ width: 140 }}><Progress pct={o.progress} /></td>
                <td><button className="btn-ghost" style={{ padding: "4px 12px", fontSize: 12, borderRadius: 6 }}>Ver</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

Object.assign(window, { Pedidos });

function OrderStatusBadge({ s }) {
  if (s === "Facturado") return <Badge variant="ok">Facturado</Badge>;
  if (s === "Lanzado") return <Badge variant="info">Lanzado</Badge>;
  if (s === "Retenido Finanzas") return <Badge variant="err">Retenido</Badge>;
  if (s === "Validación Precios") return <Badge variant="warn">Validación</Badge>;
  return <Badge variant="neutral">{s}</Badge>;
}

Object.assign(window, { Pedidos, OrderStatusBadge });
