/* global React, PRODUCTS, brl, Icon, STATUS, STATUS_LABEL */
const { useState: useSpd } = React;

function namesOf(P) { return P.map((p) => (p.brand + " " + p.model).trim()); }
function makePriceOf(P) { return (name) => { const p = P.find((x) => (x.brand + " " + x.model).trim() === name); return p ? p.price : 0; }; }
function calcTotal(items, priceOf) { return items.reduce((s, it) => s + priceOf(it.name) * (parseInt(it.qty, 10) || 0), 0); }

function blankDraft(names) {
  return { id: "", cliente: "", bairro: "", fone: "", status: "novo",
    itens: [{ name: names[0], qty: 1 }], total: 0, manual: false, _new: true };
}
function toDraft(o) {
  return { ...o, itens: o.itens.map(([name, qty]) => ({ name, qty })), manual: false, _new: false };
}

/* ============================================================ EDITOR (modal) */
function OrderEditor({ draft, setDraft, onSave, onClose, names, priceOf }) {
  const d = draft;
  const setItem = (i, patch) => setDraft((e) => ({ ...e, itens: e.itens.map((it, idx) => idx === i ? { ...it, ...patch } : it) }));
  const addItem = () => setDraft((e) => ({ ...e, itens: [...e.itens, { name: names[0], qty: 1 }] }));
  const delItem = (i) => setDraft((e) => ({ ...e, itens: e.itens.filter((_, idx) => idx !== i) }));
  const liveTotal = d.manual ? (parseFloat(d.total) || 0) : calcTotal(d.itens, priceOf);
  const valid = d.cliente.trim() && d.itens.some((it) => it.name && (parseInt(it.qty, 10) || 0) > 0);

  return (
    <div className="adm-modal-scrim" onClick={onClose}>
      <div className="adm-modal" onClick={(e) => e.stopPropagation()}>
        <div className="adm-modal-h">
          <div>
            <h3>{d._new ? "Novo pedido" : "Editar " + d.id}</h3>
            <div className="sub">{d._new ? "Cadastre um pedido manualmente" : "Altere os dados e salve"}</div>
          </div>
          <button className="adm-modal-x" onClick={onClose}><Icon k="close" size={20} /></button>
        </div>

        <div className="adm-modal-body">
          <div className="ord-grid">
            <div className="field"><label>Cliente</label>
              <input value={d.cliente} onChange={(e) => setDraft((x) => ({ ...x, cliente: e.target.value }))} placeholder="Nome do cliente" autoFocus /></div>
            <div className="field"><label>Bairro</label>
              <input value={d.bairro} onChange={(e) => setDraft((x) => ({ ...x, bairro: e.target.value }))} placeholder="Ex: Cohama" /></div>
            <div className="field"><label>WhatsApp</label>
              <input value={d.fone} onChange={(e) => setDraft((x) => ({ ...x, fone: e.target.value }))} placeholder="5598900000000" /></div>
            <div className="field"><label>Status</label>
              <select value={d.status} onChange={(e) => setDraft((x) => ({ ...x, status: e.target.value }))}>
                {STATUS.map((s) => <option key={s} value={s}>{STATUS_LABEL[s]}</option>)}
              </select></div>
          </div>

          <div className="ord-items">
            <div className="ord-items-h"><label>Itens do pedido</label>
              <span style={{ color: "var(--dim)", fontSize: 12, fontWeight: 700 }}>{d.itens.length} {d.itens.length === 1 ? "item" : "itens"}</span></div>
            {d.itens.map((it, i) => (
              <div className="ord-item-row" key={i}>
                <select value={it.name} onChange={(e) => setItem(i, { name: e.target.value })}>
                  {names.map((n) => <option key={n}>{n}</option>)}
                </select>
                <input type="number" min="1" value={it.qty} onChange={(e) => setItem(i, { qty: e.target.value })} />
                <button className="icon-btn danger" onClick={() => delItem(i)} disabled={d.itens.length === 1}
                  style={d.itens.length === 1 ? { opacity: .4, pointerEvents: "none" } : null}><Icon k="trash" size={15} /></button>
              </div>
            ))}
            <button className="ord-add-item" onClick={addItem}><Icon k="plus" size={15} /> Adicionar item</button>
          </div>

          <div className="ord-total">
            <span className="lbl">
              Total
              <label className="mini-toggle">
                <input type="checkbox" checked={d.manual} onChange={(e) => setDraft((x) => ({ ...x, manual: e.target.checked, total: e.target.checked ? calcTotal(x.itens, priceOf).toFixed(2) : x.total }))} />
                editar manual
              </label>
            </span>
            {d.manual
              ? <input type="number" step="0.01" value={d.total} onChange={(e) => setDraft((x) => ({ ...x, total: e.target.value }))} />
              : <span className="val">{brl(liveTotal)}</span>}
          </div>
        </div>

        <div className="adm-modal-foot">
          <button className="btn btn-ghost" onClick={onClose}>Cancelar</button>
          <button className="btn btn-yellow" onClick={onSave} disabled={!valid} style={!valid ? { opacity: .5, pointerEvents: "none" } : null}>
            <Icon k="check" size={18} /> {d._new ? "Criar pedido" : "Salvar"}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ============================================================ PEDIDOS */
function Pedidos({ products, orders, setOrders, cycleStatus }) {
  const P = products || PRODUCTS;
  const names = namesOf(P);
  const priceOf = makePriceOf(P);
  const [f, setF] = useSpd("todos");
  const [draft, setDraft] = useSpd(null);
  const list = f === "todos" ? orders : orders.filter((o) => o.status === f);

  const openNew = () => setDraft(blankDraft(names));
  const openEdit = (o) => setDraft(toDraft(o));
  const close = () => setDraft(null);
  const del = (id) => { if (window.confirm("Excluir o pedido " + id + "?")) setOrders((os) => os.filter((o) => o.id !== id)); };

  const save = () => {
    const e = draft;
    const items = e.itens.filter((it) => it.name && (parseInt(it.qty, 10) || 0) > 0).map((it) => [it.name, parseInt(it.qty, 10) || 1]);
    if (!e.cliente.trim() || items.length === 0) return;
    const total = e.manual ? (parseFloat(e.total) || 0) : calcTotal(e.itens, priceOf);
    if (e._new) {
      const nums = orders.map((o) => parseInt(String(o.id).replace("#", ""), 10)).filter((n) => !isNaN(n));
      const id = "#" + ((nums.length ? Math.max(...nums) : 1042) + 1);
      setOrders((os) => [{ id, cliente: e.cliente, bairro: e.bairro || "—", fone: e.fone, status: e.status, hora: "agora", itens: items, total }, ...os]);
    } else {
      setOrders((os) => os.map((o) => o.id === e.id ? { ...o, cliente: e.cliente, bairro: e.bairro, fone: e.fone, status: e.status, itens: items, total } : o));
    }
    close();
  };

  return (
    <>
      <div className="adm-toolbar">
        <div className="tabs">
          {["todos", ...STATUS].map((s) => (
            <button key={s} className={"tab" + (f === s ? " on" : "")} onClick={() => setF(s)}>{s === "todos" ? "Todos" : STATUS_LABEL[s]}</button>
          ))}
        </div>
        <button className="btn btn-yellow" style={{ marginLeft: "auto" }} onClick={openNew}><Icon k="plus" size={18} /> Novo pedido</button>
      </div>

      <div className="tbl-wrap">
        <table className="tbl">
          <thead><tr><th>Pedido</th><th>Cliente</th><th>Itens</th><th>Total</th><th>Status</th><th style={{ textAlign: "right" }}>Ações</th></tr></thead>
          <tbody>
            {list.map((o) => (
              <tr key={o.id}>
                <td><div className="t-name">{o.id}</div><div className="t-sub">{o.hora}</div></td>
                <td><div className="t-name">{o.cliente}</div><div className="t-sub">{o.bairro}</div></td>
                <td style={{ maxWidth: 280 }}>{o.itens.map((it, i) => <div key={i} style={{ fontSize: 13 }}>{it[1]}× {it[0]}</div>)}</td>
                <td style={{ fontFamily: "var(--font-display)", fontSize: 18 }}>{brl(o.total)}</td>
                <td><span className={"pill " + o.status} onClick={() => cycleStatus(o.id)} title="Clique p/ avançar status"><span className="d" />{STATUS_LABEL[o.status]}</span></td>
                <td>
                  <div className="row-actions">
                    <button className="icon-btn edit" onClick={() => openEdit(o)} title="Editar pedido"><Icon k="edit" size={16} /></button>
                    <button className="icon-btn danger" onClick={() => del(o.id)} title="Excluir pedido"><Icon k="trash" size={16} /></button>
                    {o.fone && <a className="icon-btn" style={{ color: "#25D366" }} href={"https://wa.me/" + o.fone} target="_blank" rel="noreferrer" title="WhatsApp"><Icon k="wa" size={16} /></a>}
                  </div>
                </td>
              </tr>
            ))}
            {list.length === 0 && <tr><td colSpan="6" style={{ textAlign: "center", color: "var(--dim)", padding: 40 }}>Nenhum pedido nesse status.</td></tr>}
          </tbody>
        </table>
      </div>
      <p style={{ color: "var(--dim)", fontSize: 13, marginTop: 14 }}>
        Clique na etiqueta de status para avançar (Novo → Confirmado → Entregue), ou use <Icon k="edit" size={12} /> para editar itens e valores.
      </p>

      {draft && <OrderEditor draft={draft} setDraft={setDraft} onSave={save} onClose={close} names={names} priceOf={priceOf} />}
    </>
  );
}

Object.assign(window, { Pedidos });
