/* ---------- Stock write-off / إتلاف المواد (multi-item) ---------- */
function WriteoffModal({ open, items, warehouses, onClose, onWriteoff }) {
  const { useState, useEffect } = React;
  const blankLine = () => ({ key: Math.random().toString(36).slice(2), sku: "", qty: "" });
  const [from, setFrom] = useState("");
  const [reason, setReason] = useState("");
  const [note, setNote] = useState("");
  const [lines, setLines] = useState([blankLine()]);
  const [errs, setErrs] = useState({});

  const srcItems = items.filter((i) => i.type !== "service" && i.wh === from && i.stock > 0);
  const itemBySku = (sku) => srcItems.find((i) => i.sku === sku);
  const labelFor = (i) => i.name + " · " + i.sku + " (" + i.stock + ")";
  const usedSkus = lines.map((l) => l.sku).filter(Boolean);

  useEffect(() => {
    if (open) { setFrom(""); setReason(""); setNote(""); setLines([blankLine()]); setErrs({}); }
  }, [open]);

  if (!open) return null;

  const setLine = (key, patch) => setLines((xs) => xs.map((l) => (l.key === key ? { ...l, ...patch } : l)));
  const removeLine = (key) => setLines((xs) => {
    const next = xs.filter((l) => l.key !== key);
    if (next.length === 0 || next[next.length - 1].sku) next.push(blankLine());
    return next;
  });
  const pickLine = (key, label) => {
    const hit = srcItems.find((i) => labelFor(i) === label);
    setLines((xs) => {
      let next = xs.map((l) => (l.key === key ? { ...l, sku: hit ? hit.sku : "" } : l));
      const last = next[next.length - 1];
      const usedAfter = next.map((l) => l.sku).filter(Boolean);
      if (last.sku && srcItems.length > usedAfter.length) next = [...next, blankLine()];
      return next;
    });
  };

  const filledLines = lines.filter((l) => l.sku && (parseInt(l.qty, 10) || 0) > 0);
  const totalUnits = filledLines.reduce((s, l) => s + (parseInt(l.qty, 10) || 0), 0);
  const totalLoss = filledLines.reduce((s, l) => { const it = itemBySku(l.sku); return s + (parseInt(l.qty, 10) || 0) * ((it && it.cost) || 0); }, 0);

  const save = () => {
    const e = {};
    if (!from) e.from = T("wo.errWarehouse");
    if (!reason) e.reason = T("wo.errReason");
    const valid = [];
    lines.forEach((l) => {
      if (!l.sku && !l.qty) return;
      const it = itemBySku(l.sku);
      const q = parseInt(l.qty, 10);
      if (!it) { e.lines = T("trf.errPickItem"); return; }
      if (isNaN(q) || q <= 0) { e.lines = T("trf.errQtyAboveZero"); return; }
      if (q > it.stock) { e.lines = T("wo.errOnlyOnHand", { stock: it.stock, name: it.name, wh: TV(from) }); return; }
      valid.push({ item: it, qty: q });
    });
    if (!e.lines && valid.length === 0) e.lines = T("wo.errAddOneItem");
    setErrs(e);
    if (Object.keys(e).length) return;
    onWriteoff(from, reason, note.trim(), valid);
  };

  return (
    <Modal open={true} onClose={onClose} title={T("wo.title")} width={640}
      sub={T("wo.sub")}
      footer={
        <div className="je-foot">
          <span className="inv-foot-total">
            {totalUnits > 0
              ? T("wo.unitsLossSummary", { units: totalUnits, loss: money(totalLoss) })
              : T("trf.nothingAddedYet")}
          </span>
          <div className="btnrow">
            <Btn onClick={onClose}>{T("common.cancel")}</Btn>
            <Btn variant="danger" icon="trash" onClick={save}>{T("wo.writeOff")}</Btn>
          </div>
        </div>
      }>
      <div className="formgrid">
        <Field label={T("inv.warehouse")} error={errs.from}>
          <SearchSelect options={warehouses} placeholder={T("wo.locationPlaceholder")} value={from}
            onChange={(v) => { setFrom(v); setLines([blankLine()]); }} />
        </Field>
        <Field label={T("common.reason")} error={errs.reason}>
          <SearchSelect options={D.writeoffReasons} placeholder={T("wo.reasonPlaceholder")}
            value={reason} onChange={setReason} />
        </Field>
      </div>

      <div className="field">
        <div className="inv-items-head">
          <span className="field-label" style={{ margin: 0 }}>{T("wo.itemsToWriteOff")}</span>
          {errs.lines ? <span className="field-err">{errs.lines}</span> : null}
        </div>
        {!from ? (
          <div className="trf-empty">{T("wo.chooseWarehouseFirst")}</div>
        ) : srcItems.length === 0 ? (
          <div className="trf-empty">{T("trf.noStockAt", { wh: TV(from) })}</div>
        ) : (
          <div className="inv-items">
            <div className="trf-line trf-line-head">
              <span>{T("inv.item")}</span>
              <span className="ta-c">{T("inv.onHand")}</span>
              <span className="ta-c">{T("common.qty")}</span>
              <span></span>
            </div>
            {lines.map((l) => {
              const it = itemBySku(l.sku);
              const opts = srcItems.filter((i) => i.sku === l.sku || !usedSkus.includes(i.sku)).map(labelFor);
              return (
                <div className={"trf-line" + (it ? "" : " trf-line-blank")} key={l.key}>
                  <SearchSelect options={opts} placeholder={T("trf.chooseAnItem")}
                    value={it ? labelFor(it) : ""} onChange={(v) => pickLine(l.key, v)} />
                  <span className="trf-avail mono">{it ? it.stock : "—"}</span>
                  <div className="trf-qty">
                    <input className="input inv-cell ta-c" type="number" min="1" max={it ? it.stock : undefined}
                      placeholder="0" value={l.qty} disabled={!it}
                      onChange={(e) => setLine(l.key, { qty: e.target.value })} />
                    {it ? <button type="button" className="trf-all" onClick={() => setLine(l.key, { qty: String(it.stock) })}>{T("trf.all")}</button> : null}
                  </div>
                  {it ? (
                    <button type="button" className="inv-del" onClick={() => removeLine(l.key)} title={T("common.remove")} aria-label={T("acct.removeLine")}>
                      <Icon name="trash" size={15} />
                    </button>
                  ) : <span className="trf-del-spacer"></span>}
                </div>
              );
            })}
          </div>
        )}
      </div>

      <Field label={T("common.noteOptional")}>
        <Input placeholder={T("wo.notePlaceholder")} value={note} onChange={(e) => setNote(e.target.value)} />
      </Field>
    </Modal>
  );
}
window.WriteoffModal = WriteoffModal;
