// ============================================================
// transactions.jsx — Goods Receipt + Goods Issue screens
// ============================================================

function ReceiveScreen({ state, setState }) {
  return <TransactionScreen kind="receive" state={state} setState={setState}/>;
}
function IssueScreen({ state, setState }) {
  return <TransactionScreen kind="issue" state={state} setState={setState}/>;
}

function TransactionScreen({ kind, state, setState }) {
  const toast = useToast();
  const isReceive = kind === "receive";
  const config = isReceive ? {
    title: "รับเข้าสินค้า",
    sub: "บันทึกการรับสินค้าเข้าคลัง (Goods Receipt)",
    btnLabel: "ยืนยันรับเข้า",
    btnClass: "btn-success",
    icon: "receive",
    refLabel: "เลขที่ใบสั่งซื้อ (PO)",
    refPrefix: "PO",
    noteLabel: "หมายเหตุ / Supplier",
    notePlaceholder: "เช่น Dairy Plus Co. - ส่งวันที่ 13/05",
  } : {
    title: "จ่ายออกสินค้า",
    sub: "บันทึกการจ่ายสินค้าออกจากคลัง (Goods Issue)",
    btnLabel: "ยืนยันจ่ายออก",
    btnClass: "btn-danger",
    icon: "issue",
    refLabel: "เลขที่ใบสั่งขาย (SO)",
    refPrefix: "SO",
    noteLabel: "หมายเหตุ / ปลายทาง",
    notePlaceholder: "เช่น สาขาสุขุมวิท - หน้าร้าน",
  };

  const [scanOpen, setScanOpen] = useState(false);
  const [lines, setLines] = useState([]);
  const [ref, setRef] = useState(`${config.refPrefix}-${25000 + Math.floor(Math.random() * 9999)}`);
  const [note, setNote] = useState("");
  const [warehouseId, setWarehouseId] = useState(state.warehouses[0].id);

  const onScanProduct = (p) => {
    setScanOpen(false);
    addLine(p);
    toast(`เพิ่ม ${p.name} แล้ว`, "info");
  };

  const addLine = (p, qty = 1, locId = null) => {
    setLines(prev => {
      const existing = prev.find(l => l.sku === p.sku && l.locationId === (locId || prev.find(x => x.sku === p.sku)?.locationId));
      if (existing) {
        return prev.map(l => l === existing ? { ...l, qty: l.qty + qty } : l);
      }
      // pick first location for this SKU in selected warehouse (or empty for receive)
      const locs = state.locations.filter(l => l.warehouseId === warehouseId);
      let defaultLoc = locs[0]?.id;
      if (!isReceive) {
        // find one with stock
        const withStock = locs.find(l => (state.stock[`${p.sku}|${l.id}`] || 0) > 0);
        defaultLoc = withStock?.id || locs[0]?.id;
      }
      return [...prev, { sku: p.sku, locationId: locId || defaultLoc, qty }];
    });
  };

  const updateLine = (idx, patch) => {
    setLines(prev => prev.map((l, i) => i === idx ? { ...l, ...patch } : l));
  };
  const removeLine = (idx) => setLines(prev => prev.filter((_, i) => i !== idx));

  const totalUnits = lines.reduce((s, l) => s + Number(l.qty || 0), 0);
  const totalValue = lines.reduce((s, l) => {
    const p = state.products.find(x => x.sku === l.sku);
    return s + Number(l.qty || 0) * (p?.costPrice || 0);
  }, 0);

  const canSubmit = lines.length > 0 && lines.every(l => l.qty > 0 && l.locationId);

  // Issue: warn if line qty > available
  const issueWarnings = !isReceive ? lines.map(l => {
    const have = state.stock[`${l.sku}|${l.locationId}`] || 0;
    return l.qty > have ? `${l.sku} ที่ ${l.locationId} เหลือ ${have}` : null;
  }).filter(Boolean) : [];

  const submit = () => {
    if (!canSubmit) return;
    if (issueWarnings.length > 0) {
      toast(`ปริมาณเกินสต๊อก: ${issueWarnings[0]}`, "danger");
      return;
    }
    setState(s => {
      const newStock = { ...s.stock };
      const addedMovements = lines.map(l => {
        const key = `${l.sku}|${l.locationId}`;
        const cur = newStock[key] || 0;
        newStock[key] = isReceive ? cur + Number(l.qty) : cur - Number(l.qty);
        return {
          id: `MV-${Date.now()}-${Math.floor(Math.random() * 999)}`,
          type: kind, sku: l.sku, locationId: l.locationId,
          qty: Number(l.qty), ref, note, userId: s.currentUserId,
          date: new Date().toISOString(),
        };
      });
      const changedStock = {};
      lines.forEach(l => { changedStock[`${l.sku}|${l.locationId}`] = newStock[`${l.sku}|${l.locationId}`]; });
      DB.syncTransaction(addedMovements, changedStock);
      return { ...s, stock: newStock, movements: [...addedMovements, ...s.movements] };
    });
    toast(`${isReceive ? "รับเข้า" : "จ่ายออก"} ${totalUnits} หน่วยเรียบร้อย (${ref})`, "success");
    setLines([]);
    setRef(`${config.refPrefix}-${25000 + Math.floor(Math.random() * 9999)}`);
    setNote("");
  };

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">{config.title}</div>
          <div className="page-sub">{config.sub}</div>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 320px", gap: 14 }}>
        <div className="card card-pad-0">
          <div className="card-header">
            <h3>รายการสินค้า</h3>
            <div className="row">
              <button className="btn btn-secondary btn-sm" onClick={() => setScanOpen(true)}>
                <Icon name="scan" size={13}/> สแกนบาร์โค้ด
              </button>
              <ProductPicker products={state.products} onPick={addLine} buttonLabel="เพิ่มสินค้า"/>
            </div>
          </div>
          {lines.length === 0 ? (
            <EmptyState icon={config.icon} title="ยังไม่มีรายการสินค้า" sub="กดสแกนบาร์โค้ดหรือเพิ่มสินค้าด้วยตนเอง"/>
          ) : (
            <div className="table-wrap">
              <table className="table">
                <thead><tr>
                  <th>สินค้า</th>
                  <th>Location</th>
                  <th className="num">จำนวน</th>
                  <th className="num">มูลค่า</th>
                  <th style={{ width: 40 }}></th>
                </tr></thead>
                <tbody>
                  {lines.map((l, i) => {
                    const p = state.products.find(x => x.sku === l.sku);
                    const have = state.stock[`${l.sku}|${l.locationId}`] || 0;
                    const overflow = !isReceive && l.qty > have;
                    return (
                      <tr key={i}>
                        <td>
                          <div style={{ fontSize: 13, fontWeight: 500 }}>{p?.name}</div>
                          <div className="mono text-xs muted">{p?.sku} · {p?.barcode}</div>
                        </td>
                        <td>
                          <select className="select" style={{ width: 130, padding: "5px 8px" }}
                            value={l.locationId} onChange={e => updateLine(i, { locationId: e.target.value })}>
                            {state.locations.filter(loc => loc.warehouseId === warehouseId).map(loc => {
                              const q = state.stock[`${l.sku}|${loc.id}`] || 0;
                              return <option key={loc.id} value={loc.id}>{loc.id} {!isReceive ? `(${q})` : ""}</option>;
                            })}
                          </select>
                        </td>
                        <td className="num">
                          <input type="number" min="1" className="input"
                            style={{ width: 90, textAlign: "right", padding: "5px 8px", borderColor: overflow ? "var(--danger)" : undefined }}
                            value={l.qty} onChange={e => updateLine(i, { qty: Math.max(0, Number(e.target.value)) })}/>
                          {overflow && <div className="text-xs" style={{ color: "var(--danger)" }}>เหลือ {have}</div>}
                        </td>
                        <td className="num mono">{formatCurrency(l.qty * (p?.costPrice || 0))}</td>
                        <td>
                          <button className="btn btn-ghost btn-icon" onClick={() => removeLine(i)}>
                            <Icon name="trash" size={14}/>
                          </button>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>

        <div className="col" style={{ gap: 14 }}>
          <div className="card">
            <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600 }}>รายละเอียดเอกสาร</h3>
            <hr className="divider"/>
            <div className="col" style={{ gap: 12 }}>
              <div className="field">
                <label className="label">{config.refLabel}</label>
                <input className="input mono" value={ref} onChange={e => setRef(e.target.value)}/>
              </div>
              <div className="field">
                <label className="label">คลัง / Warehouse</label>
                <select className="select" value={warehouseId} onChange={e => setWarehouseId(e.target.value)}>
                  {state.warehouses.map(w => <option key={w.id} value={w.id}>{w.code} · {w.name}</option>)}
                </select>
              </div>
              <div className="field">
                <label className="label">{config.noteLabel}</label>
                <textarea className="textarea" rows={2} placeholder={config.notePlaceholder} value={note} onChange={e => setNote(e.target.value)}/>
              </div>
            </div>
          </div>

          <div className="card">
            <div className="row" style={{ justifyContent: "space-between" }}>
              <span className="muted text-sm">จำนวนรายการ</span>
              <span className="tnum" style={{ fontWeight: 600 }}>{lines.length}</span>
            </div>
            <div className="row" style={{ justifyContent: "space-between", marginTop: 8 }}>
              <span className="muted text-sm">หน่วยรวม</span>
              <span className="tnum" style={{ fontWeight: 600 }}>{formatNumber(totalUnits)}</span>
            </div>
            <div className="row" style={{ justifyContent: "space-between", marginTop: 8 }}>
              <span className="muted text-sm">มูลค่ารวม (ต้นทุน)</span>
              <span className="tnum" style={{ fontWeight: 600 }}>{formatCurrency(totalValue)}</span>
            </div>
            <hr className="divider"/>
            <button className={`btn ${config.btnClass}`} style={{ width: "100%" }} disabled={!canSubmit} onClick={submit}>
              <Icon name={config.icon} size={14}/> {config.btnLabel}
            </button>
            {issueWarnings.length > 0 && (
              <div style={{ marginTop: 10, padding: 9, background: "var(--danger-soft)", color: "var(--danger)", borderRadius: 6, fontSize: 12 }}>
                <strong>คำเตือน:</strong> {issueWarnings[0]}
              </div>
            )}
          </div>
        </div>
      </div>

      <BarcodeScanModal open={scanOpen} onClose={() => setScanOpen(false)} products={state.products} onScan={onScanProduct}/>
    </>
  );
}

// ============ ProductPicker — searchable dropdown ============
function ProductPicker({ products, onPick, buttonLabel = "เลือก" }) {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState("");
  const filtered = products.filter(p =>
    !q || p.name.includes(q) || p.sku.toLowerCase().includes(q.toLowerCase()) || p.barcode.includes(q)
  ).slice(0, 50);

  return (
    <>
      <button className="btn btn-accent btn-sm" onClick={() => setOpen(true)}>
        <Icon name="plus" size={13}/> {buttonLabel}
      </button>
      <Modal open={open} onClose={() => setOpen(false)} title="เลือกสินค้า">
        <div className="topbar-search" style={{ minWidth: 0, marginBottom: 10 }}>
          <Icon name="search" size={14}/>
          <input placeholder="ค้นหาด้วยชื่อ, SKU หรือบาร์โค้ด..." value={q} onChange={e => setQ(e.target.value)} autoFocus/>
        </div>
        <div style={{ maxHeight: 360, overflow: "auto" }}>
          {filtered.map(p => (
            <button key={p.sku} className="nav-item" style={{ padding: 10 }}
              onClick={() => { onPick(p); setOpen(false); setQ(""); }}>
              <Icon name="package" size={14}/>
              <div style={{ flex: 1, textAlign: "left" }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{p.name}</div>
                <div className="mono text-xs muted">{p.sku} · {p.barcode}</div>
              </div>
              <span className="badge">{p.category}</span>
            </button>
          ))}
          {filtered.length === 0 && <EmptyState icon="search" title="ไม่พบสินค้า"/>}
        </div>
      </Modal>
    </>
  );
}

Object.assign(window, { ReceiveScreen, IssueScreen, ProductPicker });
