/* ============ สินค้า / คลัง (ขายวัสดุ) ============ */
function thDateI(iso) { const d = new Date(iso); if (isNaN(d)) return ''; return d.getDate() + ' ' + D.thMonthsShort[d.getMonth()] + ' ' + String((d.getFullYear() + 543) % 100).padStart(2, '0'); }
const LOW_STOCK = 10;

function InventoryPage({ role, toast }) {
  const canEdit = role === 'owner' || role === 'staff';
  const canDelete = role === 'owner';
  const [, setVer] = useState(0);
  const refresh = () => setVer((v) => v + 1);
  const [modal, setModal] = useState(null);   // product add/edit
  const [stockIn, setStockIn] = useState(null); // รับเข้า
  const [sellOpen, setSellOpen] = useState(false);
  const [delRow, setDelRow] = useState(null);

  const list = D.products || [];

  const saveProd = async (rec, msg) => {
    const exists = (D.products || []).some((x) => x.id === rec.id);
    const res = exists ? await API.updateProduct(rec) : await API.addProduct(rec);
    if (res.ok && res.data.ok) {
      const saved = res.data.record || rec; D.products = D.products || [];
      const i = D.products.findIndex((x) => x.id === saved.id);
      if (i >= 0) D.products[i] = saved; else D.products.push(saved);
      if (msg) toast(msg); setModal(null); setStockIn(null); refresh();
      return true;
    }
    toast((res.data && (res.data.msg || res.data.error)) || 'บันทึกไม่สำเร็จ', 'warn');
    return false;
  };
  const doDelete = async () => {
    const res = await API.deleteProduct(delRow.id);
    if (res.ok && res.data.ok) { const i = D.products.findIndex((x) => x.id === delRow.id); if (i >= 0) D.products.splice(i, 1); toast('ลบสินค้าแล้ว'); refresh(); }
    else toast('ลบไม่สำเร็จ', 'warn');
    setDelRow(null);
  };

  const stockValue = list.reduce((a, p) => a + (p.stock || 0) * (p.cost || 0), 0);
  const lowN = list.filter((p) => (p.stock || 0) <= LOW_STOCK).length;

  return (
    <>
      <div className="page-head">
        <div><div className="pt">สินค้า / คลัง</div><div className="ps">วัสดุที่ซื้อมาขาย — รับเข้า · ตัดสต็อกตอนขาย · เชื่อมรายรับ/ภาษีขายอัตโนมัติ</div></div>
        <div className="spacer"></div>
        {canEdit && <button className="btn btn-ghost" onClick={() => setModal('new')}><Icon name="plus" className="ic" />เพิ่มสินค้า</button>}
        {canEdit && <button className="btn btn-primary" onClick={() => setSellOpen(true)}><Icon name="income" className="ic" />ขายสินค้า</button>}
      </div>

      <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(190px, 1fr))', marginBottom: 16 }}>
        <Stat label="รายการสินค้า" icon="docs" value={list.length} unit=" รายการ" />
        <Stat label="มูลค่าสต็อก (ทุน)" icon="bank" iconBg="var(--ok-bg)" iconColor="var(--ok)" value={D.baht(stockValue, 0)} />
        <Stat label="สินค้าใกล้หมด" icon="alert" iconBg={lowN ? 'var(--warn-bg)' : 'var(--surface-2)'} iconColor={lowN ? 'var(--warn)' : 'var(--ink-3)'} value={lowN} unit=" รายการ" sub={'คงเหลือ ≤ ' + LOW_STOCK} />
      </div>

      <div className="card">
        <div className="card-head"><h3>รายการสินค้า</h3><span className="badge muted" style={{ marginLeft: 'auto' }}>{list.length} รายการ</span></div>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead><tr><th>รหัส</th><th>ชื่อสินค้า</th><th className="c">หน่วย</th><th className="r">คงเหลือ</th><th className="r">ทุน/หน่วย</th><th className="r">ราคาขาย</th>{canEdit && <th className="c sticky-act">จัดการ</th>}</tr></thead>
            <tbody>
              {list.map((p) => {
                const low = (p.stock || 0) <= LOW_STOCK;
                return (
                  <tr key={p.id}>
                    <td className="mono" style={{ fontSize: 12.5 }}>{p.code}</td>
                    <td style={{ fontWeight: 500, minWidth: 160 }}>{p.name}</td>
                    <td className="c" style={{ color: 'var(--ink-3)' }}>{p.unit}</td>
                    <td className="r num" style={{ fontWeight: 700, color: low ? 'var(--danger)' : 'var(--ink)' }}>{D.fmt0(p.stock)}{low && <span style={{ fontSize: 10, marginLeft: 4 }}>⚠️</span>}</td>
                    <td className="r num" style={{ color: 'var(--ink-3)' }}>{D.fmt(p.cost)}</td>
                    <td className="r num" style={{ fontWeight: 600 }}>{D.fmt(p.price)}</td>
                    {canEdit && (
                      <td className="c sticky-act">
                        <div style={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
                          <button className="btn btn-soft btn-sm" onClick={() => setStockIn(p)}><Icon name="plus" className="ic" />รับเข้า</button>
                          <button className="x-btn" title="แก้ไข" onClick={() => setModal(p)}><Icon name="edit" size={16} /></button>
                          {canDelete && <button className="x-btn" title="ลบ" style={{ color: 'var(--danger)' }} onClick={() => setDelRow(p)}><Icon name="trash" size={16} /></button>}
                        </div>
                      </td>
                    )}
                  </tr>
                );
              })}
              {list.length === 0 && <tr><td colSpan={canEdit ? 7 : 6} style={{ textAlign: 'center', color: 'var(--ink-3)', padding: '26px 12px' }}>ยังไม่มีสินค้า — กด “เพิ่มสินค้า” เพื่อเริ่ม</td></tr>}
            </tbody>
          </table>
        </div>
      </div>

      {modal && <ProductModal record={modal === 'new' ? null : modal} onClose={() => setModal(null)} onSave={(rec) => saveProd(rec, modal === 'new' ? 'เพิ่มสินค้าแล้ว' : 'บันทึกแล้ว')} />}
      {stockIn && <StockInModal product={stockIn} onClose={() => setStockIn(null)} onSave={saveProd} />}
      {sellOpen && <SellModal toast={toast} onClose={() => setSellOpen(false)} onDone={() => { setSellOpen(false); refresh(); }} />}
      {delRow && (
        <Modal title="ยืนยันการลบสินค้า" icon="trash" onClose={() => setDelRow(null)}
          footer={<><button className="btn btn-ghost" onClick={() => setDelRow(null)}>ยกเลิก</button><button className="btn btn-danger" onClick={doDelete}><Icon name="trash" className="ic" />ลบ</button></>}>
          <div style={{ fontSize: 14, lineHeight: 1.7 }}>ลบสินค้า <b>{delRow.name}</b> (คงเหลือ {D.fmt0(delRow.stock)} {delRow.unit}) ใช่หรือไม่?</div>
        </Modal>
      )}
    </>
  );
}

function ProductModal({ record, onClose, onSave }) {
  const r = record || {};
  const [f, setF] = useState({ code: r.code || '', name: r.name || '', unit: r.unit || 'ถุง', cost: r.cost != null ? String(r.cost) : '', price: r.price != null ? String(r.price) : '', stock: r.stock != null ? String(r.stock) : '' });
  const [err, setErr] = useState('');
  const set = (k, v) => setF((p) => ({ ...p, [k]: v }));
  const save = () => {
    if (!f.name.trim()) { setErr('กรุณากรอกชื่อสินค้า'); return; }
    onSave({ id: r.id || ('P' + Date.now()), code: f.code.trim(), name: f.name.trim(), unit: f.unit, cost: +f.cost || 0, price: +f.price || 0, stock: +f.stock || 0 });
  };
  return (
    <Modal title={record ? 'แก้ไขสินค้า' : 'เพิ่มสินค้า'} icon="docs" onClose={onClose}
      footer={<><button className="btn btn-ghost" onClick={onClose}>ยกเลิก</button><button className="btn btn-primary" onClick={save}><Icon name="check" className="ic" />บันทึก</button></>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
        {err && <div className="callout warn" style={{ padding: '9px 12px' }}><Icon name="alert" className="ic" />{err}</div>}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 2fr', gap: 12 }}>
          <Field label="รหัสสินค้า"><input className="input mono" value={f.code} onChange={(e) => set('code', e.target.value)} placeholder="เช่น CEM-50" /></Field>
          <Field label="ชื่อสินค้า"><input className="input" value={f.name} onChange={(e) => set('name', e.target.value)} placeholder="เช่น ปูนซีเมนต์ 50 กก." /></Field>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr 1fr', gap: 12 }}>
          <Field label="หน่วย"><select className="select" value={f.unit} onChange={(e) => set('unit', e.target.value)}>{D.units.map((u) => <option key={u} value={u}>{u}</option>)}</select></Field>
          <Field label="ทุน/หน่วย"><input className="input right mono" value={f.cost} onChange={(e) => set('cost', e.target.value)} placeholder="0.00" /></Field>
          <Field label="ราคาขาย"><input className="input right mono" value={f.price} onChange={(e) => set('price', e.target.value)} placeholder="0.00" /></Field>
          <Field label="คงเหลือเริ่มต้น"><input className="input right mono" value={f.stock} onChange={(e) => set('stock', e.target.value)} placeholder="0" disabled={!!record} /></Field>
        </div>
        {record && <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>* แก้จำนวนคงเหลือผ่านปุ่ม "รับเข้า" หรือการขาย (กันสต็อกเพี้ยน)</div>}
      </div>
    </Modal>
  );
}

function StockInModal({ product, onClose, onSave }) {
  const [qty, setQty] = useState('');
  const [cost, setCost] = useState(product.cost != null ? String(product.cost) : '');
  const qn = parseFloat(qty) || 0;
  return (
    <Modal title={'รับเข้าสต็อก — ' + product.name} icon="expense" onClose={onClose}
      footer={<><button className="btn btn-ghost" onClick={onClose}>ยกเลิก</button><button className="btn btn-primary" disabled={qn <= 0} onClick={() => onSave({ ...product, stock: (product.stock || 0) + qn, cost: +cost || product.cost }, 'รับเข้า ' + D.fmt0(qn) + ' ' + product.unit + ' แล้ว')}><Icon name="check" className="ic" />รับเข้า</button></>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
        <div className="callout info" style={{ padding: '9px 12px' }}><Icon name="info" className="ic" />คงเหลือปัจจุบัน <b>{D.fmt0(product.stock)} {product.unit}</b> → หลังรับเข้า <b>{D.fmt0((product.stock || 0) + qn)} {product.unit}</b></div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label={'จำนวนรับเข้า (' + product.unit + ')'}><input className="input right mono" value={qty} onChange={(e) => setQty(e.target.value)} placeholder="0" autoFocus /></Field>
          <Field label="ทุน/หน่วย (อัปเดต)"><input className="input right mono" value={cost} onChange={(e) => setCost(e.target.value)} placeholder="0.00" /></Field>
        </div>
      </div>
    </Modal>
  );
}

function SellModal({ toast, onClose, onDone }) {
  const [lines, setLines] = useState([{ productId: '', qty: '1', price: '' }]);
  const [customer, setCustomer] = useState('');
  const [custTax, setCustTax] = useState('');
  const [payer, setPayer] = useState('company');
  const [vatType, setVatType] = useState('vat7');
  const [dateISO, setDateISO] = useState(new Date().toISOString().slice(0, 10));
  const [docNo, setDocNo] = useState('SAL-' + new Date().toISOString().slice(2, 10).replace(/-/g, '') + '-' + String(Math.floor(Math.random() * 900) + 100));
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState('');

  const prods = D.products || [];
  const setLine = (i, k, v) => setLines((ls) => ls.map((l, idx) => (idx === i ? { ...l, [k]: v } : l)));
  const pickProduct = (i, pid) => { const p = prods.find((x) => x.id === pid); setLines((ls) => ls.map((l, idx) => (idx === i ? { ...l, productId: pid, price: p ? String(p.price) : l.price } : l))); };
  const addLine = () => setLines((ls) => [...ls, { productId: '', qty: '1', price: '' }]);
  const rmLine = (i) => setLines((ls) => ls.filter((_, idx) => idx !== i));

  const lineTotal = (l) => (parseFloat(l.qty) || 0) * (parseFloat(l.price) || 0);
  const validLines = lines.filter((l) => l.productId && parseFloat(l.qty) > 0);
  const subtotal = validLines.reduce((a, l) => a + lineTotal(l), 0);
  const vat = vatType === 'vat7' ? Math.round(subtotal * 0.07 * 100) / 100 : 0;
  const total = subtotal + vat;

  const confirm = async () => {
    setErr('');
    if (!validLines.length) { setErr('เลือกสินค้าอย่างน้อย 1 รายการ'); return; }
    if (!customer.trim()) { setErr('กรุณากรอกชื่อลูกค้า'); return; }
    const over = validLines.find((l) => { const p = prods.find((x) => x.id === l.productId); return p && parseFloat(l.qty) > (p.stock || 0); });
    if (over) { const p = prods.find((x) => x.id === over.productId); setErr('สินค้า "' + p.name + '" คงเหลือไม่พอ (มี ' + D.fmt0(p.stock) + ' ' + p.unit + ')'); return; }
    setSaving(true);
    // 1) ตัดสต็อก
    for (const l of validLines) {
      const p = prods.find((x) => x.id === l.productId);
      if (p) { const upd = { ...p, stock: (p.stock || 0) - (parseFloat(l.qty) || 0) }; const res = await API.updateProduct(upd); if (res.ok && res.data.ok) { const i = D.products.findIndex((x) => x.id === p.id); if (i >= 0) D.products[i] = res.data.record || upd; } }
    }
    // 2) สร้างรายรับ (ภาษีขาย) → เชื่อม VAT/ภ.พ.30/ใบกำกับ
    const items = validLines.map((l) => { const p = prods.find((x) => x.id === l.productId); return (p ? p.name : '') + ' x' + l.qty; }).join(', ');
    const rec = {
      id: 'S' + Date.now(), docNo: docNo.trim() || '—', dateISO, date: thDateI(dateISO),
      customer: customer.trim(), custTax: custTax.trim() || '—', payer, type: vatType,
      pre: subtotal, vat, total, project: 'ขายสินค้า: ' + items, contractNo: '',
      whtRate: 0, retRate: 0, wht: 0, retention: 0, netReceived: total, status: 'passed',
    };
    const res = await API.addIncome(rec);
    setSaving(false);
    if (res.ok && res.data.ok) {
      D.income = D.income || []; D.income.push(res.data.record || rec);
      toast('บันทึกการขาย + ตัดสต็อกแล้ว');
      if (window.printInvoice) setTimeout(() => { if (confirmPrint()) window.printInvoice(res.data.record || rec); }, 50);
      onDone();
    } else toast('บันทึกไม่สำเร็จ', 'warn');
  };
  const confirmPrint = () => window.confirm('บันทึกแล้ว — ต้องการพิมพ์ใบกำกับภาษี/ใบเสร็จเลยไหม?');

  return (
    <Modal title="ขายสินค้า" icon="income" onClose={onClose} wide
      footer={<><div style={{ marginRight: 'auto', fontSize: 14 }}>รวมทั้งสิ้น <b className="num" style={{ fontSize: 17, color: 'var(--primary)' }}>{D.baht(total)}</b></div><button className="btn btn-ghost" onClick={onClose}>ยกเลิก</button><button className="btn btn-primary" onClick={confirm} disabled={saving}><Icon name="check" className="ic" />{saving ? 'กำลังบันทึก…' : 'บันทึกการขาย'}</button></>}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 13 }}>
        {err && <div className="callout warn" style={{ padding: '9px 12px' }}><Icon name="alert" className="ic" />{err}</div>}
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 12 }}>
          <Field label="ลูกค้า"><input className="input" value={customer} onChange={(e) => setCustomer(e.target.value)} placeholder="ชื่อลูกค้า" /></Field>
          <Field label="เลขผู้เสียภาษีลูกค้า"><input className="input mono" value={custTax} onChange={(e) => setCustTax(e.target.value)} placeholder="13 หลัก (ถ้ามี)" /></Field>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 12 }}>
          <Field label="เลขที่บิลขาย"><input className="input mono" value={docNo} onChange={(e) => setDocNo(e.target.value)} /></Field>
          <Field label="วันที่ขาย"><ThaiDatePicker value={dateISO} onChange={setDateISO} /></Field>
          <Field label="ภาษี"><select className="select" value={vatType} onChange={(e) => setVatType(e.target.value)}><option value="vat7">VAT 7%</option><option value="exempt">ยกเว้น VAT</option></select></Field>
        </div>

        <div style={{ background: 'var(--surface-2)', borderRadius: 11, padding: 12 }}>
          <div style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--ink-2)', marginBottom: 8 }}>รายการสินค้า</div>
          {lines.map((l, i) => {
            const p = prods.find((x) => x.id === l.productId);
            return (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '2.4fr 0.9fr 1fr 1fr 30px', gap: 8, alignItems: 'center', marginBottom: 7 }}>
                <select className="select" value={l.productId} onChange={(e) => pickProduct(i, e.target.value)}>
                  <option value="">— เลือกสินค้า —</option>
                  {prods.map((pr) => <option key={pr.id} value={pr.id}>{pr.name} (เหลือ {D.fmt0(pr.stock)} {pr.unit})</option>)}
                </select>
                <input className="input right mono" value={l.qty} onChange={(e) => setLine(i, 'qty', e.target.value)} placeholder="จำนวน" />
                <input className="input right mono" value={l.price} onChange={(e) => setLine(i, 'price', e.target.value)} placeholder="ราคา/หน่วย" />
                <div className="num" style={{ textAlign: 'right', fontWeight: 600, fontSize: 13 }}>{D.fmt(lineTotal(l))}</div>
                <button className="x-btn" style={{ color: 'var(--danger)' }} disabled={lines.length === 1} onClick={() => rmLine(i)}><Icon name="x" size={15} /></button>
              </div>
            );
          })}
          <button className="btn btn-ghost btn-sm" onClick={addLine}><Icon name="plus" className="ic" />เพิ่มรายการ</button>
        </div>

        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <div style={{ width: 280, display: 'flex', flexDirection: 'column', gap: 5, fontSize: 13.5 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}><span style={{ color: 'var(--ink-2)' }}>รวมเป็นเงิน</span><span className="num">{D.fmt(subtotal)}</span></div>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}><span style={{ color: 'var(--ink-2)' }}>VAT {vatType === 'vat7' ? '7%' : '(ยกเว้น)'}</span><span className="num">{D.fmt(vat)}</span></div>
            <div className="divider" style={{ margin: '3px 0' }}></div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 700, fontSize: 15 }}><span>รวมทั้งสิ้น</span><span className="num" style={{ color: 'var(--primary)' }}>{D.fmt(total)}</span></div>
          </div>
        </div>
        <div className="callout info" style={{ padding: '9px 12px' }}><Icon name="info" className="ic" />บันทึกแล้วระบบจะ<b>ตัดสต็อก</b> + สร้าง<b>รายรับ/ภาษีขาย</b>ให้อัตโนมัติ (เข้า ภ.พ.30) และออกใบกำกับได้</div>
      </div>
    </Modal>
  );
}

window.InventoryPage = InventoryPage;
