// operations.jsx — Receive (รับเข้า), Issue (จ่ายออก), Transfer (โอน) screens

const { useState: useState_op, useMemo: useMemo_op, useEffect: useEffect_op } = React;

// ─── Lines editor (shared by receive/issue) ─────────────────────────
function LinesEditor({ lines, setLines, mode, locationId }) {
  const { items, getStock } = useStore();
  const [pickerOpen, setPickerOpen] = useState_op(false);
  const [pickerQuery, setPickerQuery] = useState_op("");

  const filtered = items.filter(it =>
    !lines.find(l => l.sku === it.sku) &&
    (it.name.toLowerCase().includes(pickerQuery.toLowerCase()) ||
     it.sku.toLowerCase().includes(pickerQuery.toLowerCase()))
  );

  const addLine = (sku) => {
    setLines([...lines, { sku, qty: 1 }]);
    setPickerOpen(false);
    setPickerQuery("");
  };

  return (
    <div className="card" style={{overflow:"hidden"}}>
      <div className="card-head">
        <div className="card-title">รายการสินค้า</div>
        <div className="card-sub">{lines.length} รายการ</div>
        <button className="btn sm primary" style={{marginLeft:"auto"}} onClick={() => setPickerOpen(true)}>
          <Icon name="plus" size={14}/> เพิ่มสินค้า
        </button>
      </div>
      <div className="table-wrap">
        <table className="tbl">
          <thead>
            <tr>
              <th style={{width:90}}>SKU</th>
              <th>ชื่อสินค้า</th>
              {mode === "issue" && <th style={{width:90, textAlign:"right"}}>คงเหลือ</th>}
              <th style={{width:160}}>จำนวน</th>
              <th style={{width:120, textAlign:"right"}}>มูลค่า</th>
              <th style={{width:40}}></th>
            </tr>
          </thead>
          <tbody>
            {lines.length === 0 && (
              <tr><td colSpan="6">
                <EmptyState
                  icon="package"
                  title="ยังไม่มีรายการสินค้า"
                  hint="เพิ่มสินค้าจากปุ่ม + เพื่อเริ่มเอกสาร"
                  action={<button className="btn primary" onClick={() => setPickerOpen(true)}><Icon name="plus" size={14}/>เพิ่มสินค้ารายการแรก</button>}
                />
              </td></tr>
            )}
            {lines.map((line, idx) => {
              const item = items.find(i => i.sku === line.sku);
              if (!item) return null;
              const onHand = locationId ? getStock(line.sku, locationId) : 0;
              const insufficient = mode === "issue" && line.qty > onHand;
              const cost = mode === "issue" ? item.price : item.cost;
              return (
                <tr key={line.sku}>
                  <td className="cell-sku">{item.sku}</td>
                  <td>
                    <div style={{fontWeight:500}}>{item.name}</div>
                    <div style={{fontSize:11, color:"var(--text-mute)", marginTop:2}}>
                      <span className="cat-chip">{item.category}</span>
                    </div>
                  </td>
                  {mode === "issue" && (
                    <td className="cell-num">
                      <span className="num" style={{color: insufficient ? "var(--danger)" : "inherit"}}>{fmtNum(onHand)}</span>
                      <span className="muted" style={{fontSize:10.5, marginLeft:4}}>{item.unit}</span>
                    </td>
                  )}
                  <td>
                    <QtyStepper value={line.qty} onChange={(v) => {
                      const next = [...lines]; next[idx] = { ...line, qty: v }; setLines(next);
                    }}/>
                    {insufficient && <div style={{color:"var(--danger)", fontSize:11, marginTop:4}}>เกินสต๊อก!</div>}
                  </td>
                  <td className="cell-num num">{fmtMoney(cost * line.qty)}</td>
                  <td>
                    <button className="icon-btn" style={{width:30, height:30}} onClick={() => {
                      setLines(lines.filter((_, i) => i !== idx));
                    }}>
                      <Icon name="trash" size={14}/>
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      <Modal open={pickerOpen} onClose={() => setPickerOpen(false)} title="เลือกสินค้า" subtitle="ค้นหาด้วยชื่อหรือ SKU">
        <div className="fld" style={{marginBottom:10}}>
          <div className="search" style={{width:"100%"}}>
            <Icon name="search" size={15}/>
            <input className="input" autoFocus placeholder="ค้นหา..." value={pickerQuery} onChange={e => setPickerQuery(e.target.value)} style={{paddingLeft:36}}/>
          </div>
        </div>
        <div style={{maxHeight:340, overflow:"auto", margin:"0 -8px", padding:"0 8px"}}>
          {filtered.length === 0 && <EmptyState icon="search" title="ไม่พบสินค้า" hint="ลองค้นหาด้วยคำอื่น"/>}
          {filtered.map(it => (
            <div key={it.sku}
              style={{display:"flex", alignItems:"center", gap:12, padding:"10px 12px", borderRadius:9, cursor:"pointer", transition:"background 140ms"}}
              onMouseEnter={e => e.currentTarget.style.background = "rgba(109,124,255,0.08)"}
              onMouseLeave={e => e.currentTarget.style.background = "transparent"}
              onClick={() => addLine(it.sku)}
            >
              <div style={{flex:1, minWidth:0}}>
                <div style={{fontWeight:500}}>{it.name}</div>
                <div style={{fontSize:11.5, color:"var(--text-mute)", marginTop:3, display:"flex", gap:8}}>
                  <span className="mono">{it.sku}</span>
                  <span className="cat-chip">{it.category}</span>
                </div>
              </div>
              <Icon name="plus" size={16}/>
            </div>
          ))}
        </div>
      </Modal>
    </div>
  );
}

// ─── Receive screen ─────────────────────────────────────────────────
function ReceiveScreen({ initialSku, onDone }) {
  const { locations, items, receive } = useStore();
  const warehouses = locations.filter(l => l.type !== "shop");
  const [location, setLocation] = useState_op(warehouses[0]?.id || "WH-A");
  const [supplier, setSupplier] = useState_op("");
  const [refDoc, setRefDoc] = useState_op("PO-" + Math.floor(10000 + Math.random()*90000));
  const [note, setNote] = useState_op("");
  const [lines, setLines] = useState_op(initialSku ? [{ sku: initialSku, qty: 30 }] : []);

  const total = lines.reduce((a, l) => {
    const it = items.find(i => i.sku === l.sku);
    return a + (it?.cost || 0) * l.qty;
  }, 0);
  const totalUnits = lines.reduce((a, l) => a + l.qty, 0);

  const submit = () => {
    if (lines.length === 0) return;
    lines.forEach(l => receive({ sku: l.sku, loc: location, qty: l.qty, supplier, note: note || ("เอกสาร " + refDoc) }));
    setLines([]);
    setNote("");
    setRefDoc("PO-" + Math.floor(10000 + Math.random()*90000));
    if (onDone) onDone();
  };

  return (
    <div className="col gap-md">
      <div style={{display:"grid", gridTemplateColumns:"1fr 320px", gap: 14, alignItems:"flex-start"}}>
        <div className="col gap-md">
          {/* Header section */}
          <div className="card pad">
            <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap: 14}}>
              <div className="fld">
                <label>เลขที่เอกสาร PO</label>
                <input className="input mono" value={refDoc} onChange={e => setRefDoc(e.target.value)}/>
              </div>
              <div className="fld">
                <label>คลังปลายทาง</label>
                <select className="select" value={location} onChange={e => setLocation(e.target.value)}>
                  {warehouses.map(l => <option key={l.id} value={l.id}>{l.name} ({l.id})</option>)}
                </select>
              </div>
              <div className="fld">
                <label>ผู้จำหน่าย / Supplier</label>
                <input className="input" placeholder="เช่น SoundTech Co." value={supplier} onChange={e => setSupplier(e.target.value)}/>
              </div>
              <div className="fld">
                <label>วันที่รับ</label>
                <input className="input" type="text" defaultValue={new Date().toLocaleDateString("th-TH", { day:"2-digit", month:"long", year:"numeric" })}/>
              </div>
              <div className="fld" style={{gridColumn:"1 / -1"}}>
                <label>หมายเหตุ</label>
                <textarea className="input" rows={2} placeholder="ข้อความเพิ่มเติม..." value={note} onChange={e => setNote(e.target.value)}/>
              </div>
            </div>
          </div>

          <LinesEditor lines={lines} setLines={setLines} mode="receive"/>
        </div>

        {/* Summary panel */}
        <div className="card" style={{position:"sticky", top: 0}}>
          <div className="card-head">
            <div className="card-title">สรุปเอกสารรับเข้า</div>
          </div>
          <div style={{padding:"16px 18px"}}>
            <SummaryRow label="จำนวน SKU" value={fmtNum(lines.length)}/>
            <SummaryRow label="หน่วยรวม" value={fmtNum(totalUnits)}/>
            <div style={{height:1, background:"var(--border)", margin:"12px 0"}}/>
            <SummaryRow label="มูลค่ารวม (ต้นทุน)" value={fmtMoney(total)} bold/>
            <SummaryRow label="VAT 7%" value={fmtMoney(total * 0.07)}/>
            <div style={{height:1, background:"var(--border)", margin:"12px 0"}}/>
            <SummaryRow label="ยอดสุทธิ" value={fmtMoney(total * 1.07)} bold big/>

            <button className="btn ok" style={{width:"100%", marginTop:18, justifyContent:"center", padding:"11px"}} onClick={submit} disabled={lines.length===0}>
              <Icon name="check" size={15}/> ยืนยันรับเข้าสต๊อก
            </button>
            <button className="btn ghost" style={{width:"100%", marginTop:8, justifyContent:"center"}}>
              บันทึกเป็นร่าง
            </button>
            <div style={{textAlign:"center", marginTop:14, fontSize:11.5, color:"var(--text-mute)"}}>
              เมื่อยืนยัน ระบบจะเพิ่มสต๊อกในคลัง <b style={{color:"var(--text)"}}>{location}</b> โดยอัตโนมัติ
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── Issue screen ───────────────────────────────────────────────────
function IssueScreen({ onDone }) {
  const { locations, items, getStock, issue } = useStore();
  const [location, setLocation] = useState_op("WH-A");
  const [customer, setCustomer] = useState_op("");
  const [refDoc, setRefDoc] = useState_op("SO-" + Math.floor(10000 + Math.random()*90000));
  const [note, setNote] = useState_op("");
  const [lines, setLines] = useState_op([]);
  const [reason, setReason] = useState_op("sale");

  const reasons = [
    { id: "sale", label: "ขายให้ลูกค้า" },
    { id: "damage", label: "สินค้าเสียหาย" },
    { id: "sample", label: "ตัวอย่าง / Sample" },
    { id: "adjust", label: "ปรับสต๊อก" },
  ];

  const total = lines.reduce((a, l) => {
    const it = items.find(i => i.sku === l.sku);
    return a + (it?.price || 0) * l.qty;
  }, 0);
  const totalUnits = lines.reduce((a, l) => a + l.qty, 0);

  const hasInsufficient = lines.some(l => l.qty > getStock(l.sku, location));

  const submit = () => {
    if (lines.length === 0 || hasInsufficient) return;
    lines.forEach(l => issue({ sku: l.sku, loc: location, qty: l.qty, customer, note: note || (reasons.find(r => r.id === reason)?.label) }));
    setLines([]); setNote("");
    setRefDoc("SO-" + Math.floor(10000 + Math.random()*90000));
    if (onDone) onDone();
  };

  return (
    <div className="col gap-md">
      <div style={{display:"grid", gridTemplateColumns:"1fr 320px", gap: 14, alignItems:"flex-start"}}>
        <div className="col gap-md">
          <div className="card pad">
            <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap: 14}}>
              <div className="fld">
                <label>เลขที่เอกสาร SO</label>
                <input className="input mono" value={refDoc} onChange={e => setRefDoc(e.target.value)}/>
              </div>
              <div className="fld">
                <label>คลังต้นทาง</label>
                <select className="select" value={location} onChange={e => setLocation(e.target.value)}>
                  {locations.map(l => <option key={l.id} value={l.id}>{l.name} ({l.id})</option>)}
                </select>
              </div>
              <div className="fld">
                <label>ลูกค้า / ผู้รับ</label>
                <input className="input" placeholder="เช่น ออเดอร์ออนไลน์ #1234" value={customer} onChange={e => setCustomer(e.target.value)}/>
              </div>
              <div className="fld">
                <label>เหตุผลการจ่ายออก</label>
                <select className="select" value={reason} onChange={e => setReason(e.target.value)}>
                  {reasons.map(r => <option key={r.id} value={r.id}>{r.label}</option>)}
                </select>
              </div>
              <div className="fld" style={{gridColumn:"1 / -1"}}>
                <label>หมายเหตุ</label>
                <textarea className="input" rows={2} placeholder="ข้อความเพิ่มเติม..." value={note} onChange={e => setNote(e.target.value)}/>
              </div>
            </div>
          </div>

          <LinesEditor lines={lines} setLines={setLines} mode="issue" locationId={location}/>
        </div>

        <div className="card" style={{position:"sticky", top: 0}}>
          <div className="card-head">
            <div className="card-title">สรุปเอกสารจ่ายออก</div>
          </div>
          <div style={{padding:"16px 18px"}}>
            <SummaryRow label="จำนวน SKU" value={fmtNum(lines.length)}/>
            <SummaryRow label="หน่วยรวม" value={fmtNum(totalUnits)}/>
            <div style={{height:1, background:"var(--border)", margin:"12px 0"}}/>
            <SummaryRow label="มูลค่ารวม (ขาย)" value={fmtMoney(total)} bold big/>
            {hasInsufficient && (
              <div className="chip err" style={{marginTop:14, width:"100%", justifyContent:"center", padding:"8px"}}>
                <Icon name="alert" size={13}/> มีรายการที่สต๊อกไม่พอ
              </div>
            )}
            <button className="btn danger" style={{width:"100%", marginTop:18, justifyContent:"center", padding:"11px"}} onClick={submit} disabled={lines.length===0 || hasInsufficient}>
              <Icon name="out" size={15}/> ยืนยันจ่ายออกสต๊อก
            </button>
            <button className="btn ghost" style={{width:"100%", marginTop:8, justifyContent:"center"}}>
              บันทึกเป็นร่าง
            </button>
            <div style={{textAlign:"center", marginTop:14, fontSize:11.5, color:"var(--text-mute)"}}>
              สต๊อกจะถูกหักจาก <b style={{color:"var(--text)"}}>{location}</b> ทันทีเมื่อยืนยัน
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

function SummaryRow({ label, value, bold, big }) {
  return (
    <div style={{display:"flex", justifyContent:"space-between", alignItems:"baseline", padding:"5px 0"}}>
      <span style={{fontSize: big ? 13 : 12.5, color: "var(--text-mute)"}}>{label}</span>
      <span className="num" style={{fontSize: big ? 19 : 14, fontWeight: bold ? 700 : 500}}>{value}</span>
    </div>
  );
}

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