/* Driftwood — Transactions with filters, search, and bulk actions
   (select, select-all, bulk delete, bulk categorize, bulk reassign person). */
const TX_CATS = ["Groceries", "Dining out", "Transportation", "Utilities", "Shopping", "Health", "Subscription", "Income", "Other"];
const TX_CAT_COLOR = { Groceries: "teal", "Dining out": "amber", Transportation: "violet", Utilities: "sky", Shopping: "rose", Health: "green", Subscription: "pink", Income: "green", Other: "blue" };

function TransactionModal({ initial, onClose, onSave, onDelete }) {
  const names = window.useMemberNames();
  const isIncome0 = initial.amount > 0;
  const [f, setF] = React.useState({
    type: isIncome0 ? "income" : "expense",
    merchant: initial.merchant,
    amount: String(Math.abs(initial.amount)),
    cat: initial.cat === "Income" ? "Groceries" : initial.cat,
    who: initial.who,
    date: initial.date,
  });
  const set = (k) => (v) => setF({ ...f, [k]: v });
  const save = () => {
    const amt = parseFloat(f.amount) || 0;
    if (!f.merchant.trim() || !amt) { onClose(); return; }
    const cat = f.type === "income" ? "Income" : f.cat;
    onSave({
      ...initial,
      merchant: f.merchant.trim(),
      amount: f.type === "income" ? Math.abs(amt) : -Math.abs(amt),
      cat,
      who: f.who,
      date: f.date.trim() || initial.date,
      color: f.type === "income" ? "green" : (TX_CAT_COLOR[cat] || initial.color),
    }, initial);
    onClose();
  };
  return (
    <Modal title="Edit transaction" sub="Update this entry in your shared tracker."
      onClose={onClose} onSave={save} saveLabel="Save" onDelete={() => { onDelete(initial); onClose(); }}>
      <div className="field" style={{ marginBottom: 14 }}>
        <div className="segctl">
          <button className={f.type === "expense" ? "on" : ""} onClick={() => setF({ ...f, type: "expense" })}>Expense</button>
          <button className={f.type === "income" ? "on" : ""} onClick={() => setF({ ...f, type: "income" })}>Income</button>
        </div>
      </div>
      <TextField label="Description" value={f.merchant} onChange={set("merchant")} placeholder="e.g. Whole Foods" autoFocus />
      <div className="modal-row">
        <MoneyField label="Amount" value={f.amount} onChange={set("amount")} />
        <SelectField label="Who" value={f.who} onChange={set("who")} options={names.includes(f.who) ? names : [f.who, ...names]} />
      </div>
      <div className="modal-row">
        {f.type === "expense"
          ? <SelectField label="Category" value={f.cat} onChange={set("cat")} options={TX_CATS.filter((c) => c !== "Income")} />
          : <div className="field" style={{ marginBottom: 14 }}><label>Category</label><div className="input"><input value="Income" disabled style={{ fontSize: 15, fontWeight: 500, color: "var(--dim)" }} /></div></div>}
        <TextField label="Date" value={f.date} onChange={set("date")} placeholder="e.g. May 28" />
      </div>
    </Modal>
  );
}

function ScreenTransactions({ openAdd, txns, setTxns }) {
  const { usd } = window.FP;
  const names = window.useMemberNames();
  const [who, setWho] = React.useState("All");
  const [q, setQ] = React.useState("");
  const [sel, setSel] = React.useState(() => new Set());
  const [editTx, setEditTx] = React.useState(null);

  const filtered = txns.filter((t) =>
    (who === "All" || t.who === who) &&
    (q === "" || t.merchant.toLowerCase().includes(q.toLowerCase()) || t.cat.toLowerCase().includes(q.toLowerCase()))
  );
  const inflow = filtered.filter((t) => t.amount > 0).reduce((s, t) => s + t.amount, 0);
  const outflow = filtered.filter((t) => t.amount < 0).reduce((s, t) => s + t.amount, 0);

  const allSelected = filtered.length > 0 && filtered.every((t) => sel.has(t));
  const someSelected = filtered.some((t) => sel.has(t));

  const toggle = (t) => setSel((prev) => { const n = new Set(prev); n.has(t) ? n.delete(t) : n.add(t); return n; });
  const toggleAll = () => setSel((prev) => {
    const n = new Set(prev);
    if (allSelected) filtered.forEach((t) => n.delete(t));
    else filtered.forEach((t) => n.add(t));
    return n;
  });
  const clearSel = () => setSel(new Set());

  const bulkDelete = () => { setTxns((list) => list.filter((t) => !sel.has(t))); clearSel(); };
  const bulkCategorize = (cat) => {
    if (!cat) return;
    setTxns((list) => list.map((t) => sel.has(t) ? { ...t, cat, color: TX_CAT_COLOR[cat] || t.color } : t));
    clearSel();
  };
  const bulkAssign = (w) => {
    if (!w) return;
    setTxns((list) => list.map((t) => sel.has(t) ? { ...t, who: w } : t));
    clearSel();
  };

  const selCount = filtered.filter((t) => sel.has(t)).length;

  const saveEdit = (data, original) => setTxns((list) => list.map((t) => (t === original ? data : t)));
  const deleteTx = (t) => { setTxns((list) => list.filter((x) => x !== t)); setSel((prev) => { const n = new Set(prev); n.delete(t); return n; }); };

  return (
    <>
      <ScreenHeader title="Transactions" sub={`${filtered.length} entries · shared tracker`}>
        <button className="btn btn-primary" onClick={openAdd}><Icon name="plus" /> Add Entry</button>
      </ScreenHeader>

      <div className="content">
        <div className="grid g3">
          {[["Money in", inflow, "var(--pos)"], ["Money out", outflow, "var(--hi)"], ["Net", inflow + outflow, inflow + outflow >= 0 ? "var(--pos)" : "var(--neg)"]].map(([l, v, c]) => (
            <div className="stat" key={l}>
              <div className="stat-label">{l}</div>
              <div className="num stat-val" style={{ color: c }}>{usd(v, { cents: true, sign: v > 0 })}</div>
            </div>
          ))}
        </div>

        <div className="card">
          {/* Filter row OR bulk-action bar */}
          {selCount === 0 ? (
            <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 18, flexWrap: "wrap" }}>
              <div className="segctl" style={{ width: "auto", flex: "0 0 auto" }}>
                {["All", ...names].map((w) => (
                  <button key={w} className={who === w ? "on" : ""} onClick={() => setWho(w)} style={{ padding: "9px 18px" }}>{w}</button>
                ))}
              </div>
              <div className="input" style={{ flex: 1, minWidth: 200 }}>
                <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search merchant or category…" style={{ fontSize: 14, fontWeight: 400 }} />
              </div>
            </div>
          ) : (
            <div className="bulkbar">
              <span className="bulkbar-count">{selCount} selected</span>
              <div className="bulkbar-actions">
                <div className="bulk-select">
                  <select defaultValue="" onChange={(e) => { bulkCategorize(e.target.value); e.target.value = ""; }}>
                    <option value="" disabled>Categorize…</option>
                    {TX_CATS.map((c) => <option key={c} value={c}>{c}</option>)}
                  </select>
                </div>
                <div className="bulk-select">
                  <select defaultValue="" onChange={(e) => { bulkAssign(e.target.value); e.target.value = ""; }}>
                    <option value="" disabled>Assign to…</option>
                    {names.map((w) => <option key={w} value={w}>{w}</option>)}
                  </select>
                </div>
                <button className="bulk-btn danger" onClick={bulkDelete}><Icon name="transactions" style={{ width: 15, height: 15 }} /> Delete</button>
                <button className="bulk-btn" onClick={clearSel}>Clear</button>
              </div>
            </div>
          )}

          <table className="tbl tbl-sel">
            <thead><tr>
              <th style={{ width: 38 }}><label className="ck"><input type="checkbox" checked={allSelected} ref={(el) => { if (el) el.indeterminate = !allSelected && someSelected; }} onChange={toggleAll} /><span /></label></th>
              <th>Transaction</th><th>Category</th><th>Who</th><th>Date</th><th>Amount</th><th style={{ width: 44 }}></th>
            </tr></thead>
            <tbody>
              {filtered.map((t, i) => {
                const on = sel.has(t);
                return (
                  <tr key={i} className={on ? "row-sel" : ""} onClick={() => toggle(t)} style={{ cursor: "pointer" }}>
                    <td onClick={(e) => e.stopPropagation()}><label className="ck"><input type="checkbox" checked={on} onChange={() => toggle(t)} /><span /></label></td>
                    <td><div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                      <span style={{ width: 32, height: 32, borderRadius: 9, background: `color-mix(in oklch, ${PALETTE[t.color]} 20%, transparent)`, display: "flex", alignItems: "center", justifyContent: "center", color: PALETTE[t.color], fontSize: 13, fontWeight: 700 }}>{t.merchant[0]}</span>
                      <span style={{ fontWeight: 500, whiteSpace: "nowrap" }}>{t.merchant}</span>
                    </div></td>
                    <td><span className="tag">{t.cat}</span></td>
                    <td style={{ color: "var(--mid)" }}>{t.who}</td>
                    <td style={{ color: "var(--dim)", fontSize: 13 }}>{t.date}</td>
                    <td className="num" style={{ fontWeight: 600, color: t.amount > 0 ? "var(--pos)" : "var(--hi)" }}>{usd(t.amount, { cents: true, sign: t.amount > 0 })}</td>
                    <td onClick={(e) => e.stopPropagation()} style={{ textAlign: "right" }}>
                      <button className="tx-edit" title="Edit transaction" onClick={() => setEditTx(t)}><Icon name="budgets" style={{ width: 15, height: 15 }} /></button>
                    </td>
                  </tr>
                );
              })}
              {filtered.length === 0 && (
                <tr><td colSpan="7" style={{ textAlign: "center", color: "var(--dim)", padding: "32px 0" }}>No matching transactions.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {editTx && <TransactionModal initial={editTx} onClose={() => setEditTx(null)} onSave={saveEdit} onDelete={deleteTx} />}
    </>
  );
}
window.ScreenTransactions = ScreenTransactions;
