// ============================================================
// stock.jsx — Stock list + product detail drawer
// ============================================================

function StockScreen({ state, setState }) {
  const toast = useToast();
  const [q, setQ] = useState("");
  const [cat, setCat] = useState("all");
  const [status, setStatus] = useState("all");
  const [detailSku, setDetailSku] = useState(null);
  const [productForm, setProductForm] = useState(null); // null | {p, _existing?}
  const [confirmDelete, setConfirmDelete] = useState(null);

  const openCreate = () => setProductForm({});
  const openEdit = (p) => { setProductForm({ ...p, _existing: true }); };

  const saveProduct = (p) => {
    const clean = { ...p, _existing: undefined };
    setState(s => {
      let products = [...s.products];
      if (p._existing) {
        products = products.map(x => x.sku === p.sku ? { ...x, ...clean } : x);
        toast(`บันทึกการแก้ไข ${p.name}`, "success");
      } else {
        products = [...products, clean];
        toast(`เพิ่มสินค้า ${p.name}`, "success");
      }
      return { ...s, products };
    });
    DB.upsertProduct(clean);
    setProductForm(null);
  };

  const doDelete = (sku) => {
    const p = state.products.find(x => x.sku === sku);
    setState(s => {
      const newStock = {};
      Object.entries(s.stock).forEach(([k, q]) => {
        if (!k.startsWith(sku + "|")) newStock[k] = q;
      });
      return {
        ...s,
        products: s.products.filter(x => x.sku !== sku),
        stock: newStock,
        movements: s.movements.filter(m => m.sku !== sku),
      };
    });
    DB.deleteProduct(sku);
    toast(`ลบสินค้า ${p?.name || sku} เรียบร้อย`, "success");
  };

  const categories = useMemo(() => ["all", ...new Set(state.products.map(p => p.category))], [state.products]);

  const rows = useMemo(() => {
    return state.products.map(p => {
      const qty = getStockBySKU(state, p.sku);
      const locations = getLocationsForSKU(state, p.sku);
      const value = qty * p.costPrice;
      let st = "ok";
      if (qty <= 0) st = "out";
      else if (qty < p.reorderPoint) st = "low";
      return { ...p, qty, locations, value, st };
    }).filter(r => {
      if (q && !(r.name.includes(q) || r.sku.toLowerCase().includes(q.toLowerCase()) || r.barcode.includes(q))) return false;
      if (cat !== "all" && r.category !== cat) return false;
      if (status !== "all" && r.st !== status) return false;
      return true;
    });
  }, [state, q, cat, status]);

  const summary = useMemo(() => ({
    total: rows.length,
    low: rows.filter(r => r.st === "low").length,
    out: rows.filter(r => r.st === "out").length,
    value: rows.reduce((s, r) => s + r.value, 0),
  }), [rows]);

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">รายการสินค้า / สต๊อก</div>
          <div className="page-sub">{summary.total} รายการ · มูลค่ารวม {formatCurrency(summary.value)}</div>
        </div>
        <div className="row">
          <button className="btn btn-secondary">
            <Icon name="download" size={13}/> Export
          </button>
          <button className="btn btn-accent" onClick={openCreate}>
            <Icon name="plus" size={13}/> เพิ่มสินค้า
          </button>
        </div>
      </div>

      <div className="card card-pad-0">
        <div style={{ padding: 14, display: "flex", gap: 10, alignItems: "center", borderBottom: "1px solid var(--border)", flexWrap: "wrap" }}>
          <div className="topbar-search" style={{ minWidth: 280 }}>
            <Icon name="search" size={14}/>
            <input placeholder="ค้นหาด้วยชื่อ, SKU, บาร์โค้ด..." value={q} onChange={e => setQ(e.target.value)}/>
          </div>
          <select className="select" style={{ width: "auto" }} value={cat} onChange={e => setCat(e.target.value)}>
            {categories.map(c => <option key={c} value={c}>{c === "all" ? "ทุกหมวด" : c}</option>)}
          </select>
          <select className="select" style={{ width: "auto" }} value={status} onChange={e => setStatus(e.target.value)}>
            <option value="all">ทุกสถานะ</option>
            <option value="ok">พร้อมจำหน่าย</option>
            <option value="low">ต่ำกว่าจุดสั่งซื้อ</option>
            <option value="out">หมดสต๊อก</option>
          </select>
          <div className="spacer"/>
          <div className="row" style={{ gap: 10, fontSize: 12, color: "var(--fg-3)" }}>
            <span className="badge badge-warn">Low: {summary.low}</span>
            <span className="badge badge-danger">Out: {summary.out}</span>
          </div>
        </div>

        <div className="table-wrap">
          <table className="table">
            <thead><tr>
              <th>สินค้า</th>
              <th>SKU</th>
              <th>หมวดหมู่</th>
              <th className="num">คงเหลือ</th>
              <th>Locations</th>
              <th className="num">จุดสั่งซื้อ</th>
              <th className="num">มูลค่า</th>
              <th>สถานะ</th>
              <th style={{ width: 110 }}></th>
            </tr></thead>
            <tbody>
              {rows.map(r => (
                <tr key={r.sku} className="clickable">
                  <td onClick={() => setDetailSku(r.sku)}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{r.name}</div>
                    <div className="mono text-xs muted">{r.barcode}</div>
                  </td>
                  <td className="mono text-xs" onClick={() => setDetailSku(r.sku)}>{r.sku}</td>
                  <td onClick={() => setDetailSku(r.sku)}><span className="badge">{r.category}</span></td>
                  <td className="num tnum" style={{ fontWeight: 600 }} onClick={() => setDetailSku(r.sku)}>{formatNumber(r.qty)} <span className="muted text-xs">{r.unit}</span></td>
                  <td onClick={() => setDetailSku(r.sku)}>
                    <div className="row" style={{ gap: 4 }}>
                      {r.locations.slice(0, 3).map(l => (
                        <span key={l.locationId} className="badge text-xs mono">{l.locationId}</span>
                      ))}
                      {r.locations.length > 3 && <span className="text-xs muted">+{r.locations.length - 3}</span>}
                    </div>
                  </td>
                  <td className="num tnum muted" onClick={() => setDetailSku(r.sku)}>{formatNumber(r.reorderPoint)}</td>
                  <td className="num tnum" onClick={() => setDetailSku(r.sku)}>{formatCurrency(r.value)}</td>
                  <td onClick={() => setDetailSku(r.sku)}><StockBadge qty={r.qty} reorderPoint={r.reorderPoint}/></td>
                  <td>
                    <div className="row" style={{ gap: 2 }}>
                      <button className="btn btn-ghost btn-icon" title="ดูรายละเอียด" onClick={(e) => { e.stopPropagation(); setDetailSku(r.sku); }}>
                        <Icon name="eye" size={14}/>
                      </button>
                      <button className="btn btn-ghost btn-icon" title="แก้ไข" onClick={(e) => { e.stopPropagation(); openEdit(r); }}>
                        <Icon name="edit" size={14}/>
                      </button>
                      <button className="btn btn-ghost btn-icon" title="ลบ" onClick={(e) => { e.stopPropagation(); setConfirmDelete(r); }}>
                        <Icon name="trash" size={14}/>
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
          {rows.length === 0 && <EmptyState icon="search" title="ไม่พบสินค้า" sub="ลองเปลี่ยนคำค้นหรือตัวกรอง"/>}
        </div>
      </div>

      <ProductDetailDrawer
        open={!!detailSku}
        sku={detailSku}
        state={state}
        onClose={() => setDetailSku(null)}
      />

      <ProductForm
        open={!!productForm}
        initial={productForm}
        state={state}
        onSave={saveProduct}
        onClose={() => setProductForm(null)}
      />

      <ConfirmDialog
        open={!!confirmDelete}
        title="ยืนยันการลบสินค้า"
        message={confirmDelete?.qty > 0
          ? `"${confirmDelete?.name}" ยังมีสต๊อกคงเหลือ ${formatNumber(confirmDelete?.qty)} หน่วย — การลบจะลบสต๊อกและประวัติการเคลื่อนไหวทั้งหมด คุณแน่ใจหรือไม่?`
          : `ต้องการลบ "${confirmDelete?.name}" หรือไม่?`}
        danger
        onConfirm={() => doDelete(confirmDelete.sku)}
        onClose={() => setConfirmDelete(null)}
      />
    </>
  );
}

function ProductDetailDrawer({ open, sku, state, onClose }) {
  if (!open || !sku) return null;
  const p = state.products.find(x => x.sku === sku);
  if (!p) return null;

  const locations = getLocationsForSKU(state, sku);
  const totalQty = getStockBySKU(state, sku);
  const totalValue = totalQty * p.costPrice;

  // last 30 days movement for this SKU
  const movements = state.movements.filter(m => m.sku === sku).slice(0, 8);

  // chart: daily net for last 14 days
  const chart = useMemo(() => {
    const days = [];
    const now = new Date("2026-05-13T23:59:59");
    for (let d = 13; d >= 0; d--) {
      const dt = new Date(now); dt.setDate(now.getDate() - d);
      days.push({ date: dt, key: dt.toISOString().slice(0, 10), receive: 0, issue: 0 });
    }
    state.movements.filter(m => m.sku === sku).forEach(m => {
      const day = days.find(d => d.key === m.date.slice(0, 10));
      if (day) day[m.type] += m.qty;
    });
    return days;
  }, [state.movements, sku]);

  return (
    <Modal open={open} onClose={onClose} title="รายละเอียดสินค้า" size="lg" footer={
      <>
        <button className="btn btn-secondary" onClick={onClose}>ปิด</button>
      </>
    }>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
        <div>
          <div style={{
            background: "var(--surface-2)",
            borderRadius: "var(--radius)",
            height: 140,
            display: "grid",
            placeItems: "center",
            backgroundImage: "repeating-linear-gradient(45deg, var(--surface-2), var(--surface-2) 10px, var(--bg) 10px, var(--bg) 11px)",
            border: "1px solid var(--border)",
          }}>
            <span className="mono text-xs muted">PRODUCT IMAGE · {p.sku}</span>
          </div>
          <h2 style={{ margin: "14px 0 4px", fontSize: 18, fontWeight: 600, letterSpacing: "-0.01em" }}>{p.name}</h2>
          <div className="row" style={{ gap: 8, marginBottom: 12 }}>
            <span className="badge">{p.category}</span>
            <span className="mono text-xs muted">{p.sku}</span>
            <span className="mono text-xs muted">· {p.barcode}</span>
          </div>

          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8, marginTop: 14 }}>
            <KV k="ราคาทุน" v={formatCurrency(p.costPrice) + "/" + p.unit}/>
            <KV k="ราคาขาย" v={formatCurrency(p.sellPrice) + "/" + p.unit}/>
            <KV k="Supplier" v={p.supplier}/>
            <KV k="อายุการเก็บ" v={p.shelfLife + " วัน"}/>
            <KV k="จุดสั่งซื้อ" v={formatNumber(p.reorderPoint) + " " + p.unit}/>
            <KV k="หน่วย" v={p.unit}/>
          </div>
        </div>

        <div>
          <div className="card" style={{ padding: 14 }}>
            <div className="muted text-xs uppercase" style={{ marginBottom: 4 }}>คงเหลือทั้งหมด</div>
            <div style={{ fontSize: 32, fontWeight: 600, letterSpacing: "-0.025em" }}>
              <AnimatedNumber value={totalQty}/> <span className="muted text-sm" style={{ fontWeight: 400 }}>{p.unit}</span>
            </div>
            <div className="muted text-xs">มูลค่า {formatCurrency(totalValue)}</div>
            <div style={{ marginTop: 10 }}><StockBadge qty={totalQty} reorderPoint={p.reorderPoint}/></div>
          </div>

          <div style={{ marginTop: 14 }}>
            <div className="text-xs uppercase muted" style={{ marginBottom: 6 }}>การกระจายตาม Location</div>
            <div className="col" style={{ gap: 6 }}>
              {locations.map(l => {
                const loc = state.locations.find(x => x.id === l.locationId);
                const wh = state.warehouses.find(w => w.id === loc?.warehouseId);
                return (
                  <div key={l.locationId} className="row" style={{
                    justifyContent: "space-between",
                    padding: "6px 10px",
                    background: "var(--surface-2)",
                    borderRadius: 6,
                  }}>
                    <div className="row" style={{ gap: 8 }}>
                      <span className="mono text-xs" style={{ background: "var(--surface)", padding: "1px 6px", borderRadius: 4 }}>{l.locationId}</span>
                      <span className="text-xs muted">{wh?.name}</span>
                    </div>
                    <span className="tnum" style={{ fontWeight: 600 }}>{formatNumber(l.qty)}</span>
                  </div>
                );
              })}
              {locations.length === 0 && <div className="muted text-xs">ไม่มีสต๊อกใน location ใด</div>}
            </div>
          </div>
        </div>
      </div>

      <hr className="divider" style={{ margin: "20px 0" }}/>

      <div>
        <div className="text-xs uppercase muted" style={{ marginBottom: 8 }}>การเคลื่อนไหว 14 วัน</div>
        <SkuChart data={chart}/>
      </div>

      <hr className="divider" style={{ margin: "20px 0" }}/>

      <div>
        <div className="text-xs uppercase muted" style={{ marginBottom: 8 }}>การเคลื่อนไหวล่าสุด</div>
        <table className="table">
          <thead><tr>
            <th>เวลา</th><th>ประเภท</th><th>Location</th><th>Ref</th><th className="num">จำนวน</th>
          </tr></thead>
          <tbody>
            {movements.map(m => (
              <tr key={m.id}>
                <td className="mono text-xs muted">{formatShortDate(m.date)} {new Date(m.date).toTimeString().slice(0,5)}</td>
                <td><MovementBadge type={m.type}/></td>
                <td className="mono text-xs">{m.locationId}</td>
                <td className="mono text-xs">{m.ref}</td>
                <td className="num tnum">{m.type === "receive" ? "+" : "−"}{formatNumber(m.qty)}</td>
              </tr>
            ))}
            {movements.length === 0 && <tr><td colSpan="5"><div className="muted text-xs" style={{ textAlign: "center", padding: 12 }}>ยังไม่มีการเคลื่อนไหว</div></td></tr>}
          </tbody>
        </table>
      </div>
    </Modal>
  );
}

function KV({ k, v }) {
  return (
    <div style={{ padding: "6px 0" }}>
      <div className="text-xs muted">{k}</div>
      <div style={{ fontSize: 13, fontWeight: 500 }}>{v}</div>
    </div>
  );
}

function SkuChart({ data }) {
  const w = 460, h = 120;
  const padL = 28, padR = 8, padT = 8, padB = 16;
  const iw = w - padL - padR;
  const ih = h - padT - padB;
  const maxY = Math.max(20, ...data.flatMap(d => [d.receive, d.issue]));
  const stepX = iw / (data.length - 1);
  const yScale = (v) => padT + ih - (v / maxY) * ih;
  const barW = Math.max(3, stepX * 0.32);

  const pts = data.map((d, i) => [padL + i * stepX, yScale(d.receive)]);
  const linePath = `M${pts.map(p => p.join(",")).join(" L")}`;

  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: h }}>
      <g className="chart-grid">
        {[0, 0.5, 1].map(t => <line key={t} x1={padL} x2={padL + iw} y1={padT + ih * (1-t)} y2={padT + ih * (1-t)}/>)}
      </g>
      {data.map((d, i) => {
        const x = padL + i * stepX - barW/2;
        const barH = (d.issue / maxY) * ih;
        return <rect key={i} x={x} y={padT + ih - barH} width={barW} height={barH} fill="var(--danger)" opacity="0.7" rx="1"
          className="bar-animate" style={{ animationDelay: `${i * 25}ms` }}/>;
      })}
      <path d={linePath} fill="none" stroke="var(--success)" strokeWidth="2" className="chart-line animate"/>
    </svg>
  );
}

Object.assign(window, { StockScreen });
