/* Transactions.jsx — ฟอร์มรับเข้า / จ่ายออก (เชื่อมสต๊อก + auto-tag โลเคชั่น) */
const { useState: txUseState } = React;

function LineRow({ line, mode, onChange, onRemove, s }) {
  const it = s.itemOf(line.sku);
  const cat = it ? s.catOf(line.sku) : null;
  /* โลเคชั่นที่เลือกได้ */
  const avail = mode === "out" ? s.locationsOf(line.sku) : s.locations;
  const maxQty = mode === "out" ? ((s.stock[line.loc] || {})[line.sku] || 0) : null;
  const over = mode === "out" && line.qty && Number(line.qty) > maxQty;

  return (
    <div style={{ display: "grid", gridTemplateColumns: "1fr 110px 150px 38px", gap: 10, alignItems: "start", padding: 12, border: `1px solid ${over ? "var(--red)" : "var(--line)"}`, borderRadius: 12, background: "var(--surface-2)" }}>
      {/* item */}
      <div>
        <select className="select" value={line.sku} onChange={e => onChange({ ...line, sku: e.target.value, loc: "" })}>
          <option value="">— เลือกสินค้า —</option>
          {s.CATEGORIES.map(c => (
            <optgroup label={c.name} key={c.id}>
              {s.ITEMS.filter(i => i.cat === c.id).map(i => <option key={i.sku} value={i.sku}>{i.name}</option>)}
            </optgroup>
          ))}
        </select>
        {it && <div style={{ fontSize: 11.5, color: "var(--muted-2)", marginTop: 5, display: "flex", gap: 8 }}>
          <span className="num">{line.sku}</span>·<span>คงเหลือรวม {s.fmt(s.stockBySku[line.sku] || 0)} {it.unit}</span>
        </div>}
      </div>
      {/* qty */}
      <div>
        <input className="input" type="number" min="1" placeholder="จำนวน" value={line.qty}
          onChange={e => onChange({ ...line, qty: e.target.value })} style={{ textAlign: "right" }} />
        {it && <div style={{ fontSize: 11.5, color: "var(--muted-2)", marginTop: 5, textAlign: "right" }}>{it.unit}</div>}
      </div>
      {/* location */}
      <div>
        <select className="select" value={line.loc} onChange={e => onChange({ ...line, loc: e.target.value })} disabled={!line.sku}>
          <option value="">{mode === "out" ? "— จากโลเคชั่น —" : "— เก็บที่ —"}</option>
          {mode === "out"
            ? avail.map(l => <option key={l.code} value={l.code}>{l.code} (มี {s.fmt(l.qty)})</option>)
            : avail.map(l => <option key={l.code} value={l.code}>{l.code}{cat && l.zone === ({steel:"A",cement:"B",paint:"C",pipe:"D",elec:"D",hw:"C"})[cat.id] ? " ✓" : ""}</option>)
          }
        </select>
        {over && <div style={{ fontSize: 11.5, color: "var(--red)", marginTop: 5, fontWeight: 600 }}>เกินคงเหลือ (มี {s.fmt(maxQty)})</div>}
        {mode === "out" && !over && line.loc && <div style={{ fontSize: 11.5, color: "var(--muted-2)", marginTop: 5 }}>คงเหลือช่อง {s.fmt(maxQty)}</div>}
      </div>
      <button className="icon-btn" style={{ width: 38, height: 40, color: "var(--muted-2)" }} onClick={onRemove} title="ลบรายการ"><Icons.trash size={17}/></button>
    </div>
  );
}

function TxnPage({ mode, go }) {
  const s = useStore();
  const isIn = mode === "in";
  const [party, setParty] = txUseState("");
  const [user, setUser] = txUseState(s.USERS[0]);
  const [note, setNote] = txUseState("");
  const [lines, setLines] = txUseState([{ sku: "", qty: "", loc: "" }]);
  const [confirm, setConfirm] = txUseState(false);

  const docNo = s.nextDoc(mode);
  const parties = isIn ? s.SUPPLIERS : s.CUSTOMERS;

  const setLine = (idx, l) => setLines(ls => ls.map((x, i) => i === idx ? l : x));
  const addLine = () => setLines(ls => [...ls, { sku: "", qty: "", loc: "" }]);
  const rmLine = (idx) => setLines(ls => ls.length > 1 ? ls.filter((_, i) => i !== idx) : ls);

  const validLines = lines.filter(l => l.sku && Number(l.qty) > 0 && l.loc);
  const overLines = mode === "out" && lines.some(l => l.sku && l.loc && Number(l.qty) > ((s.stock[l.loc] || {})[l.sku] || 0));
  const canSubmit = party && validLines.length > 0 && !overLines && validLines.length === lines.filter(l => l.sku || l.qty || l.loc).length;

  const totalUnits = validLines.reduce((a, l) => a + Number(l.qty), 0);
  const totalValue = validLines.reduce((a, l) => a + Number(l.qty) * (s.itemOf(l.sku)?.price || 0), 0);

  const [saving, setSaving] = txUseState(false);
  const submit = async () => {
    setSaving(true);
    const payload = { party, user, note, lines: validLines };
    const id = isIn ? await s.receive(payload) : await s.issue(payload);
    setSaving(false);
    setConfirm(false);
    if (id) go("dashboard");
  };

  const accent = isIn ? "var(--green)" : "var(--primary-600)";
  const accentSoft = isIn ? "var(--green-soft)" : "var(--primary-soft)";

  return (
    <div className="page fade-up" style={{ maxWidth: 1000 }}>
      <div className="page-head" style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 14, flexWrap: "wrap" }}>
        <div style={{ display: "flex", gap: 14, alignItems: "center" }}>
          <span style={{ width: 46, height: 46, borderRadius: 13, background: accentSoft, color: accent, display: "grid", placeItems: "center" }}>
            {isIn ? <Icons.receive size={24}/> : <Icons.issue size={24}/>}
          </span>
          <div>
            <h2>{isIn ? "รับสินค้าเข้าคลัง" : "จ่ายสินค้าออก"}</h2>
            <p>{isIn ? "บันทึกการรับวัสดุจากผู้ขาย — ระบบจะแท็กเข้าโลเคชั่นอัตโนมัติ" : "เบิก/จ่ายวัสดุออกจากคลัง — ตัดสต๊อกตามโลเคชั่นที่เลือก"}</p>
          </div>
        </div>
        <span className="badge badge-gray" style={{ fontFamily: "var(--mono)", fontSize: 13, padding: "6px 12px" }}>เลขที่ {docNo}</span>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: 16 }}>
        {/* ข้อมูลเอกสาร */}
        <Card>
          <SectionHead title="ข้อมูลเอกสาร" />
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }} className="tx-meta">
            <div className="field">
              <label>{isIn ? "ผู้ขาย / ซัพพลายเออร์" : "ผู้รับ / ไซต์งาน"} <span style={{ color: "var(--red)" }}>*</span></label>
              <select className="select" value={party} onChange={e => setParty(e.target.value)}>
                <option value="">— เลือก{isIn ? "ผู้ขาย" : "ผู้รับ"} —</option>
                {parties.map(p => <option key={p} value={p}>{p}</option>)}
              </select>
            </div>
            <div className="field">
              <label>ผู้บันทึก</label>
              <select className="select" value={user} onChange={e => setUser(e.target.value)}>
                {s.USERS.map(u => <option key={u} value={u}>{u}</option>)}
              </select>
            </div>
            <div className="field" style={{ gridColumn: "1 / -1" }}>
              <label>หมายเหตุ</label>
              <input className="input" placeholder={isIn ? "เช่น เลขที่ใบสั่งซื้อ / เที่ยวรถ" : "เช่น งวดงาน / ผู้เบิก"} value={note} onChange={e => setNote(e.target.value)} />
            </div>
          </div>
        </Card>

        {/* รายการสินค้า */}
        <Card>
          <SectionHead title="รายการสินค้า" sub={`${validLines.length} รายการพร้อมบันทึก`} right={
            <button className="btn btn-soft btn-sm" onClick={addLine}><Icons.plus size={16}/>เพิ่มรายการ</button>
          } />
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {lines.map((l, i) => (
              <LineRow key={i} line={l} mode={mode} s={s} onChange={(nl) => setLine(i, nl)} onRemove={() => rmLine(i)} />
            ))}
          </div>
        </Card>
      </div>

      {/* แถบสรุป + ปุ่ม */}
      <div style={{ position: "sticky", bottom: 0, marginTop: 18, background: "rgba(255,255,255,.9)", backdropFilter: "blur(10px)", border: "1px solid var(--line)", borderRadius: 16, padding: "14px 20px", boxShadow: "var(--sh-2)", display: "flex", alignItems: "center", gap: 20, flexWrap: "wrap" }}>
        <div style={{ display: "flex", gap: 26 }}>
          <div>
            <div style={{ fontSize: 12, color: "var(--muted)" }}>รวมจำนวน</div>
            <div className="num" style={{ fontSize: 19, fontWeight: 600 }}>{s.fmt(totalUnits)} <span style={{ fontSize: 13, color: "var(--muted)", fontWeight: 500 }}>หน่วย</span></div>
          </div>
          <div>
            <div style={{ fontSize: 12, color: "var(--muted)" }}>มูลค่าโดยประมาณ</div>
            <div className="num" style={{ fontSize: 19, fontWeight: 600, color: accent }}>฿{s.fmtMoney(totalValue)}</div>
          </div>
        </div>
        <div style={{ flex: 1 }}></div>
        <div style={{ display: "flex", gap: 10 }}>
          <button className="btn btn-ghost" onClick={() => go("dashboard")}>ยกเลิก</button>
          <button className="btn btn-primary" style={isIn ? { background: "var(--green)", boxShadow: "0 2px 8px rgba(15,157,88,.3)" } : null} disabled={!canSubmit} onClick={() => setConfirm(true)}>
            <Icons.check size={17}/>{isIn ? "บันทึกรับเข้า" : "บันทึกจ่ายออก"}
          </button>
        </div>
      </div>

      {confirm && (
        <Modal title={`ยืนยันการ${isIn ? "รับเข้า" : "จ่ายออก"}`} onClose={() => setConfirm(false)} footer={
          <React.Fragment>
            <button className="btn btn-ghost" onClick={() => setConfirm(false)}>กลับไปแก้ไข</button>
            <button className="btn btn-primary" style={isIn ? { background: "var(--green)" } : null} onClick={submit} disabled={saving}><Icons.check size={17}/>{saving ? "กำลังบันทึก…" : "ยืนยัน"}</button>
          </React.Fragment>
        }>
          <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14 }}>
              <span style={{ color: "var(--muted)" }}>{isIn ? "ผู้ขาย" : "ผู้รับ"}</span><span style={{ fontWeight: 600 }}>{party}</span>
            </div>
            <div style={{ borderTop: "1px solid var(--line)" }}></div>
            {validLines.map((l, i) => {
              const it = s.itemOf(l.sku);
              return (
                <div key={i} style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <ItemThumb sku={l.sku} size={34}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.name}</div>
                    <div style={{ fontSize: 12, color: "var(--muted-2)" }}>{isIn ? "เก็บที่" : "จาก"} <span className="num">{l.loc}</span></div>
                  </div>
                  <div className="num" style={{ fontWeight: 600, color: isIn ? "var(--green)" : "var(--primary-700)" }}>{isIn ? "+" : "−"}{s.fmt(l.qty)} <span style={{ fontSize: 12, color: "var(--muted)", fontWeight: 500 }}>{it.unit}</span></div>
                </div>
              );
            })}
            <div style={{ borderTop: "1px solid var(--line)" }}></div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 15, fontWeight: 600 }}>
              <span>มูลค่ารวม</span><span className="num" style={{ color: accent }}>฿{s.fmtMoney(totalValue)}</span>
            </div>
          </div>
        </Modal>
      )}
    </div>
  );
}
window.TxnPage = TxnPage;
