/* NGIPL PLM: Master price list view */
const { useState, useEffect, useMemo, useRef } = React;

function MasterView({ nav, toast }) {
  const state = PLM.useStore();
  const [search, setSearch] = useState("");
  const [catFilter, setCatFilter] = useState("all");
  const [bulkOpen, setBulkOpen] = useState(false);
  const [editProduct, setEditProduct] = useState(null); // product object or "new"
  const grouped = PLM.groupedProducts();
  const nums = PLM.numberMap();
  const q = search.trim().toLowerCase();

  const bands = grouped
    .filter((b) => catFilter === "all" || b.cat.id === catFilter)
    .map((b) => ({
      cat: b.cat,
      groups: b.groups
        .map((g) => ({
          sub: g.sub,
          items: g.items.filter((p) => !q || p.name.toLowerCase().includes(q) || (p.note || "").toLowerCase().includes(q)),
        }))
        .filter((g) => g.items.length),
    }))
    .filter((b) => b.groups.length);
  const visibleCount = bands.reduce((a, b) => a + b.groups.reduce((x, g) => x + g.items.length, 0), 0);

  /* Drag to reorder. Mouse drags from anywhere on the row, touch drags from the grip.
     A move is limited to the item's own section, so the category never changes. */
  const [drag, setDrag] = useState(null); // { id, name, over, after, x, y }
  const dragRef = useRef(null);
  const wrapRef = useRef(null);

  function startDrag(e, p, groupKey) {
    if (e.button !== undefined && e.button !== 0) return;
    const fromGrip = !!e.target.closest(".drag-grip");
    if (!fromGrip && (e.pointerType !== "mouse" || e.target.closest("input, button, select, textarea, a"))) return;
    if (fromGrip) e.preventDefault();
    const d = { id: p.id, name: p.name, groupKey, startX: e.clientX, startY: e.clientY, x: e.clientX, y: e.clientY, active: fromGrip, over: null, after: false };
    dragRef.current = d;
    if (d.active) setDrag({ ...d });

    function locate(x, y) {
      const el = document.elementFromPoint(x, y);
      const row = el && el.closest("tr.item-row[data-pid]");
      if (!row || row.getAttribute("data-group") !== d.groupKey) return;
      const r = row.getBoundingClientRect();
      d.over = row.getAttribute("data-pid");
      d.after = y > r.top + r.height / 2;
    }
    let raf = 0;
    function autoScroll() {
      raf = 0;
      if (!d.active) return;
      const box = wrapRef.current;
      const inner = box && box.scrollHeight > box.clientHeight + 1 ? box.getBoundingClientRect() : null;
      const top = inner ? inner.top : 0, bottom = inner ? inner.bottom : window.innerHeight;
      const edge = 48;
      let dy = 0;
      if (d.y < top + edge) dy = -Math.ceil((top + edge - d.y) / 4);
      else if (d.y > bottom - edge) dy = Math.ceil((d.y - (bottom - edge)) / 4);
      if (dy) {
        if (inner) box.scrollTop += dy; else window.scrollBy(0, dy);
        locate(d.x, d.y);
        setDrag({ ...d });
        raf = requestAnimationFrame(autoScroll);
      }
    }
    function onMove(ev) {
      d.x = ev.clientX; d.y = ev.clientY;
      if (!d.active) {
        if (Math.abs(d.x - d.startX) + Math.abs(d.y - d.startY) < 6) return;
        d.active = true;
        document.body.classList.add("is-reordering");
      }
      ev.preventDefault();
      locate(d.x, d.y);
      setDrag({ ...d });
      if (!raf) raf = requestAnimationFrame(autoScroll);
    }
    function finish(commit) {
      window.removeEventListener("pointermove", onMove);
      window.removeEventListener("pointerup", onUp);
      window.removeEventListener("pointercancel", onCancel);
      window.removeEventListener("keydown", onKey);
      if (raf) cancelAnimationFrame(raf);
      document.body.classList.remove("is-reordering");
      dragRef.current = null;
      setDrag(null);
      if (commit && d.active && d.over && d.over !== d.id) {
        const no = PLM.moveProduct(d.id, d.over, d.after);
        if (no) toast(d.name + " moved to #" + no);
      }
    }
    function onUp() { finish(true); }
    function onCancel() { finish(false); }
    function onKey(ev) { if (ev.key === "Escape") finish(false); }
    window.addEventListener("pointermove", onMove, { passive: false });
    window.addEventListener("pointerup", onUp);
    window.addEventListener("pointercancel", onCancel);
    window.addEventListener("keydown", onKey);
    if (fromGrip) document.body.classList.add("is-reordering");
  }

  function commitRate(p, rate) {
    PLM.updateProduct(p.id, { rate });
    toast(p.name + " updated to ₹" + PLM.fmtRate(rate));
  }

  return (
    <div data-screen-label="Master Price List">
      <div className="toolbar">
        <div className="search-box">
          <ISearch size={15}></ISearch>
          <input className="f-input" placeholder="Search items…" value={search} onChange={(e) => setSearch(e.target.value)} />
        </div>
        <select className="f-select" style={{ width: 210, maxWidth: "100%" }} value={catFilter} onChange={(e) => setCatFilter(e.target.value)}>
          <option value="all">All categories</option>
          {state.categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
        </select>
        <span className="caption">{visibleCount} of {state.products.length} items</span>
        <div className="spacer"></div>
        <WefChip state={state}></WefChip>
        <Btn variant="secondary" size="sm" onClick={() => setBulkOpen(true)}><IPercent size={13}></IPercent> Update prices</Btn>
        <Btn size="sm" onClick={() => setEditProduct("new")}><IPlus size={13}></IPlus> Add item</Btn>
      </div>

      <div className="panel panel--strong plm-table-wrap master-rows" ref={wrapRef}>
        <table className="plm-table">
          <thead>
            <tr>
              <th className="col-no">#</th>
              <th>Item</th>
              <th className="num" style={{ width: 90 }}>Rate ₹</th>
              <th className="col-unit" style={{ width: 80 }}>Unit</th>
              <th className="num col-gst" style={{ width: 64 }}>GST</th>
              <th className="num col-pack" style={{ width: 90 }}>Pack size</th>
              <th className="num col-outer" style={{ width: 100 }}>Outer pack size</th>
              <th style={{ width: 56 }}></th>
            </tr>
          </thead>
          <tbody>
            {bands.map((band) => (
              <React.Fragment key={band.cat.id}>
                <tr className="cat-band"><td colSpan={8}><span className="band-cell"><CatIcon catId={band.cat.id} size={18}></CatIcon><span>{band.cat.name}</span></span></td></tr>
                {band.groups.map((g, gi) => (
                  <React.Fragment key={g.sub ? g.sub.id : "loose" + gi}>
                    {g.sub ? <tr className="sub-band"><td colSpan={8}>{g.sub.name}</td></tr> : null}
                    {g.items.map((p) => {
                      const groupKey = band.cat.id + "|" + (g.sub ? g.sub.id : "");
                      const dropAt = drag && drag.active && drag.over === p.id && drag.over !== drag.id ? (drag.after ? "after" : "before") : null;
                      return (
                        <ProductRow key={p.id} p={p} no={nums[p.id]} groupKey={groupKey}
                          dragging={!!(drag && drag.active && drag.id === p.id)} dropAt={dropAt}
                          onDragStart={(e) => startDrag(e, p, groupKey)}
                          onRate={(r) => commitRate(p, r)}
                          onEdit={() => setEditProduct(p)}></ProductRow>
                      );
                    })}
                  </React.Fragment>
                ))}
              </React.Fragment>
            ))}
          </tbody>
        </table>
        {visibleCount === 0 ? <div style={{ padding: 32, textAlign: "center" }} className="caption">No items match.</div> : null}
      </div>

      {drag && drag.active ? (
        <div className="drag-ghost" style={{ left: drag.x + 14, top: drag.y + 10 }}>{drag.name}</div>
      ) : null}
      {bulkOpen ? <BulkDialog onClose={() => setBulkOpen(false)} toast={toast}></BulkDialog> : null}
      {editProduct ? (
        <ProductDialog product={editProduct === "new" ? null : editProduct}
          onClose={() => setEditProduct(null)} toast={toast}></ProductDialog>
      ) : null}
    </div>
  );
}

function ProductRow({ p, no, groupKey, dragging, dropAt, onDragStart, onRate, onEdit }) {
  return (
    <tr className={"item-row" + (dragging ? " is-dragging" : "") + (dropAt ? " drop-" + dropAt : "")}
      data-pid={p.id} data-group={groupKey} onPointerDown={onDragStart}>
      <td className="col-no">{no}</td>
      <td>
        <div className="item-name-line">
          <span className="drag-grip" title="Drag to reorder" aria-hidden="true">
            <svg width="10" height="16" viewBox="0 0 10 16" fill="currentColor"><circle cx="2.5" cy="3" r="1.5"></circle><circle cx="7.5" cy="3" r="1.5"></circle><circle cx="2.5" cy="8" r="1.5"></circle><circle cx="7.5" cy="8" r="1.5"></circle><circle cx="2.5" cy="13" r="1.5"></circle><circle cx="7.5" cy="13" r="1.5"></circle></svg>
          </span>
          <span>{p.name}</span>
        </div>
        {p.note ? <div className="item-note">{p.note}</div> : null}
        <div className="row-meta">#{no} · {p.unit} · GST {PLM.fmtGst(p.gst)} · Pack {PLM.fmtPack(p.packSize)} · Outer {PLM.fmtPack(p.outerPack)}</div>
      </td>
      <td className="num rate"><RateCell value={p.rate} onCommit={onRate}></RateCell></td>
      <td className="col-unit">{p.unit}</td>
      <td className="num col-gst">{PLM.fmtGst(p.gst)}</td>
      <td className="num col-pack">{PLM.fmtPack(p.packSize)}</td>
      <td className="num col-outer">{PLM.fmtPack(p.outerPack)}</td>
      <td>
        <span className="row-actions">
          <IconBtn title="Edit item" onClick={onEdit}><IPencil size={14}></IPencil></IconBtn>
        </span>
      </td>
    </tr>
  );
}

function WefChip({ state }) {
  return (
    <span className="chip" title="Effective date, changed by an admin under Settings">
      <ICalendar size={12}></ICalendar> W.E.F. {state.settings.wef}
    </span>
  );
}

/* ---------- Bulk price update ---------- */
function BulkDialog({ onClose, toast }) {
  const state = PLM.useStore();
  const [scope, setScope] = useState("all");
  const [mode, setMode] = useState("pct");
  const [value, setValue] = useState("");
  const [round, setRound] = useState("0.05");
  const [note, setNote] = useState("");

  const scopeOptions = [{ value: "all", label: "All items" }];
  state.categories.forEach((c) => {
    scopeOptions.push({ value: "cat:" + c.id, label: c.name });
    c.subs.forEach((s) => scopeOptions.push({ value: "sub:" + c.id + ":" + s.id, label: "· " + c.name + " · " + s.name }));
  });

  function inScope(p) {
    if (scope === "all") return true;
    const parts = scope.split(":");
    if (parts[0] === "cat") return p.categoryId === parts[1];
    return p.categoryId === parts[1] && p.subId === parts[2];
  }
  const v = parseFloat(value);
  const valid = !isNaN(v) && v !== 0;
  function computeNew(rate) {
    if (!valid) return null;
    let nv = mode === "pct" ? rate * (1 + v / 100) : rate + v;
    const step = parseFloat(round);
    if (step) nv = Math.round(nv / step) * step;
    nv = Math.round(nv * 10000) / 10000;
    return nv < 0 ? 0 : nv;
  }
  const affected = state.products.filter(inScope);
  const preview = valid
    ? affected.map((p) => ({ p, nv: computeNew(p.rate) })).filter((x) => Math.abs(x.nv - x.p.rate) > 0.00005)
    : [];

  function apply() {
    const scopeLabel = scopeOptions.find((o) => o.value === scope).label.replace(/^· /, "");
    const desc = (mode === "pct" ? (v > 0 ? "+" : "") + v + "%" : (v > 0 ? "+₹" : "−₹") + Math.abs(v)) + " on " + scopeLabel;
    const n = PLM.bulkUpdate(preview.map((x) => x.p.id), computeNew, "Bulk update: " + desc, note);
    const staleAfter = PLM.totalStale();
    toast("Updated " + n + " rates (" + desc + ")" + (staleAfter ? ", " + staleAfter + " special prices flagged for review" : ""));
    onClose();
  }

  return (
    <Dialog title="Update prices" onClose={onClose} width={640}
      footer={
        <React.Fragment>
          <Btn variant="ghost" size="sm" onClick={onClose}>Cancel</Btn>
          <Btn size="sm" disabled={!preview.length} onClick={apply}>Apply to {preview.length} items</Btn>
        </React.Fragment>
      }>
      <div className="f-stack">
        <div className="f-row">
          <Field label="Scope">
            <select className="f-select" value={scope} onChange={(e) => setScope(e.target.value)}>
              {scopeOptions.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
            </select>
          </Field>
          <Field label="Adjustment">
            <div style={{ display: "flex", gap: 8 }}>
              <Seg options={[{ value: "pct", label: "%" }, { value: "abs", label: "₹" }]} value={mode} onChange={setMode}></Seg>
              <input className="f-input" style={{ flex: 1, minWidth: 0 }} placeholder={mode === "pct" ? "e.g. 5" : "e.g. 0.10"}
                value={value} onChange={(e) => setValue(e.target.value)} />
            </div>
          </Field>
          <Field label="Round to">
            <select className="f-select" value={round} onChange={(e) => setRound(e.target.value)}>
              <option value="0">No rounding</option>
              <option value="0.0001">₹0.0001</option>
              <option value="0.001">₹0.001</option>
              <option value="0.01">₹0.01</option>
              <option value="0.05">₹0.05</option>
              <option value="0.10">₹0.10</option>
              <option value="0.5">₹0.50</option>
              <option value="1">₹1</option>
            </select>
          </Field>
        </div>
        <Field label="Note (shown in history)">
          <input className="f-input" placeholder="e.g. Raw material cost increase, FY 26-27" value={note} onChange={(e) => setNote(e.target.value)} />
        </Field>
        <div>
          <div className="f-label">Preview{valid ? " (" + preview.length + " of " + affected.length + " rates change)" : ""}</div>
          <div className="panel" style={{ maxHeight: 240, overflow: "auto" }}>
            {!valid ? (
              <div className="caption" style={{ padding: 16 }}>Enter an adjustment to preview changes.</div>
            ) : (
              <table className="plm-table">
                <tbody>
                  {preview.slice(0, 200).map(({ p, nv }) => (
                    <tr key={p.id}>
                      <td>{p.name}</td>
                      <td className="num tnum" style={{ width: 90, color: "var(--text-faint)" }}>₹{PLM.fmtRate(p.rate)}</td>
                      <td style={{ width: 30, color: "var(--text-faint)" }}><IArrowR size={12}></IArrowR></td>
                      <td className="num tnum rate" style={{ width: 90 }}>₹{PLM.fmtRate(nv)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </div>
        <div className="caption">
          The special price list is not changed. A special price on an updated item is flagged for review under Special price list.
        </div>
      </div>
    </Dialog>
  );
}

/* ---------- Add / edit product ---------- */
function ProductDialog({ product, onClose, toast }) {
  const state = PLM.useStore();
  const isNew = !product;
  const [f, setF] = useState(() => ({
    name: product ? product.name : "",
    note: product ? product.note || "" : "",
    categoryId: product ? product.categoryId : state.categories[0].id,
    subId: product ? product.subId || "" : "",
    rate: product ? String(product.rate) : "",
    unit: product ? product.unit : "Pcs",
    packSize: product ? (product.packSize === null || product.packSize === undefined ? "" : String(product.packSize)) : "",
    gst: product ? String(product.gst) : "18",
    outerPack: product ? (product.outerPack === null || product.outerPack === undefined ? "" : String(product.outerPack)) : "",
  }));
  const [confirmDel, setConfirmDel] = useState(false);
  const cat = PLM.catById(f.categoryId);
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
  const rateN = parseFloat(f.rate);
  const canSave = f.name.trim() && !isNaN(rateN) && rateN >= 0;

  function save() {
    const packRaw = f.packSize.trim();
    const packN = parseFloat(packRaw);
    const outerRaw = f.outerPack.trim();
    const outerN = parseFloat(outerRaw);
    const fields = {
      name: f.name.trim(), note: f.note.trim(),
      categoryId: f.categoryId, subId: f.subId || null,
      rate: Math.round(rateN * 10000) / 10000,
      unit: f.unit.trim() || "Pcs",
      packSize: packRaw === "" ? null : (!isNaN(packN) && /^[\d.]+$/.test(packRaw) ? packN : packRaw),
      gst: parseFloat(f.gst) || 0,
      outerPack: outerRaw === "" ? null : (!isNaN(outerN) && /^[\d.]+$/.test(outerRaw) ? outerN : outerRaw),
    };
    if (isNew) {
      PLM.addProduct(fields);
      toast("Added " + fields.name);
    } else {
      PLM.updateProduct(product.id, fields);
      toast("Saved " + fields.name);
    }
    onClose();
  }

  return (
    <Dialog title={isNew ? "Add item" : "Edit item"} onClose={onClose} width={620}
      footer={
        <React.Fragment>
          {!isNew ? (
            confirmDel ? (
              <span style={{ marginRight: "auto", display: "inline-flex", alignItems: "center", gap: 8 }}>
                <span className="caption">Delete this item?</span>
                <Btn variant="danger" size="sm" onClick={() => { PLM.deleteProduct(product.id); toast("Deleted " + product.name); onClose(); }}>Delete</Btn>
              </span>
            ) : (
              <Btn variant="ghost" size="sm" style={{ marginRight: "auto", color: "var(--red-700)" }} onClick={() => setConfirmDel(true)}>
                <ITrash size={13}></ITrash> Delete
              </Btn>
            )
          ) : null}
          <Btn variant="ghost" size="sm" onClick={onClose}>Cancel</Btn>
          <Btn size="sm" disabled={!canSave} onClick={save}>{isNew ? "Add item" : "Save"}</Btn>
        </React.Fragment>
      }>
      <div className="f-stack">
        <Field label="Item name">
          <input className="f-input" value={f.name} onChange={set("name")} placeholder="e.g. White Sugar (5gms)" />
        </Field>
        <Field label="Note (optional, prints under the name)">
          <input className="f-input" value={f.note} onChange={set("note")} placeholder="e.g. For date printing ₹0.10 extra, MOQ applies" />
        </Field>
        <div className="f-row">
          <Field label="Category">
            <select className="f-select" value={f.categoryId} onChange={(e) => setF({ ...f, categoryId: e.target.value, subId: "" })}>
              {state.categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </Field>
          {cat && cat.subs.length ? (
            <Field label="Sub-category">
              <select className="f-select" value={f.subId} onChange={set("subId")}>
                <option value="">None</option>
                {cat.subs.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
              </select>
            </Field>
          ) : null}
        </div>
        <div className="f-row">
          <Field label="Rate ₹ (ex-GST)">
            <input className="f-input" value={f.rate} onChange={set("rate")} placeholder="0.0000" />
          </Field>
          <Field label="Unit">
            <input className="f-input" value={f.unit} onChange={set("unit")} placeholder="Pcs / Sachets / Can" />
          </Field>
          <Field label="GST %">
            <select className="f-select" value={f.gst} onChange={set("gst")}>
              {["0", "5", "12", "18", "28"].map((g) => <option key={g} value={g}>{g}%</option>)}
            </select>
          </Field>
          <Field label="Pack size">
            <input className="f-input" value={f.packSize} onChange={set("packSize")} placeholder="e.g. 200 or 5 Ltr" />
          </Field>
          <Field label="Outer pack size">
            <input className="f-input" value={f.outerPack} onChange={set("outerPack")} placeholder="e.g. 10 or 24" />
          </Field>
        </div>
      </div>
    </Dialog>
  );
}

Object.assign(window, { MasterView });
