/* Items.jsx — รายละเอียดข้อมูลสต๊อกสินค้าแต่ละตัว */
const { useState: itUseState, useMemo: itUseMemo } = React;

function ItemImageUploader({ sku }) {
  const s = useStore();
  const it = s.itemOf(sku);
  const img = s.images[sku];
  const inputRef = React.useRef(null);

  const pick = () => inputRef.current && inputRef.current.click();
  const onFile = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    if (!file.type.startsWith("image/")) { s.pushToast("กรุณาเลือกไฟล์รูปภาพ", "warn"); return; }
    const reader = new FileReader();
    reader.onload = () => {
      /* ย่อรูปด้วย canvas ก่อนเก็บ เพื่อไม่ให้ localStorage เต็ม */
      const tmp = new Image();
      tmp.onload = () => {
        const max = 480;
        let { width: w, height: h } = tmp;
        if (w > h && w > max) { h = h * max / w; w = max; }
        else if (h > max) { w = w * max / h; h = max; }
        const cv = document.createElement("canvas");
        cv.width = w; cv.height = h;
        cv.getContext("2d").drawImage(tmp, 0, 0, w, h);
        s.setImage(sku, cv.toDataURL("image/jpeg", 0.82));
        s.pushToast("อัปเดตรูปสินค้าแล้ว");
      };
      tmp.src = reader.result;
    };
    reader.readAsDataURL(file);
    e.target.value = "";
  };

  return (
    <div style={{ marginBottom: 16 }}>
      <input ref={inputRef} type="file" accept="image/*" onChange={onFile} style={{ display: "none" }} />
      {img ? (
        <div style={{ position: "relative", borderRadius: 14, overflow: "hidden", border: "1px solid var(--line)" }}>
          <img src={img} alt={it.name} style={{ width: "100%", height: 200, objectFit: "cover", display: "block" }} />
          <div style={{ position: "absolute", right: 10, bottom: 10, display: "flex", gap: 8 }}>
            <button className="btn btn-ghost btn-sm" onClick={pick} style={{ background: "rgba(255,255,255,.92)", backdropFilter: "blur(4px)" }}><Icons.edit size={15}/>เปลี่ยนรูป</button>
            <button className="btn btn-ghost btn-sm" onClick={() => { s.setImage(sku, null); s.pushToast("ลบรูปแล้ว"); }} style={{ background: "rgba(255,255,255,.92)", backdropFilter: "blur(4px)", color: "var(--red)" }}><Icons.trash size={15}/></button>
          </div>
        </div>
      ) : (
        <button onClick={pick} style={{ width: "100%", border: "1.5px dashed var(--line)", background: "var(--surface-2)", borderRadius: 14, padding: "26px 16px", cursor: "pointer", display: "flex", flexDirection: "column", alignItems: "center", gap: 8, color: "var(--muted)", font: "inherit", transition: "all .16s" }}
          onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--primary)"; e.currentTarget.style.color = "var(--primary-700)"; }}
          onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--line)"; e.currentTarget.style.color = "var(--muted)"; }}>
          <span style={{ width: 44, height: 44, borderRadius: 12, background: "var(--primary-soft)", color: "var(--primary-600)", display: "grid", placeItems: "center" }}><Icons.plus size={22}/></span>
          <span style={{ fontWeight: 600, fontSize: 14 }}>เพิ่มรูปภาพสินค้า</span>
          <span style={{ fontSize: 12 }}>คลิกเพื่อเลือกไฟล์ภาพ (JPG, PNG)</span>
        </button>
      )}
    </div>
  );
}

function ItemDrawer({ sku, onClose, go }) {
  const s = useStore();
  const it = s.itemOf(sku);
  const qty = s.stockBySku[sku] || 0;
  const locs = s.locationsOf(sku);
  const cat = s.catOf(sku);
  const value = qty * it.price;
  const pct = Math.min(100, Math.round(qty / it.reorder * 100));
  const moves = s.movements.filter(m => m.lines.some(l => l.sku === sku)).slice(0, 8);

  return (
    <Drawer onClose={onClose}
      headIcon={<ItemThumb sku={sku} size={46}/>}
      title={it.name}
      sub={<span><span className="num">{sku}</span> · {cat.name}</span>}
      footer={
        <React.Fragment>
          <button className="btn btn-ghost" onClick={() => { onClose(); go("receive"); }}><Icons.receive size={16}/>รับเข้า</button>
          <button className="btn btn-primary" onClick={() => { onClose(); go("issue"); }}><Icons.issue size={16}/>จ่ายออก</button>
        </React.Fragment>
      }>
      {/* รูปภาพสินค้า */}
      <ItemImageUploader sku={sku} />

      {/* สรุปคงเหลือ */}
      <Card style={{ marginBottom: 16 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
          <div>
            <div style={{ fontSize: 13, color: "var(--muted)" }}>คงเหลือรวม</div>
            <div className="num" style={{ fontSize: 32, fontWeight: 600, letterSpacing: "-.02em" }}>{s.fmt(qty)} <span style={{ fontSize: 15, color: "var(--muted)", fontWeight: 500 }}>{it.unit}</span></div>
          </div>
          <StockBadge qty={qty} reorder={it.reorder} />
        </div>
        <div className="bar" style={{ marginTop: 14 }}><span style={{ width: `${pct}%`, background: qty === 0 ? "var(--red)" : qty <= it.reorder ? "var(--amber)" : "var(--green)" }}></span></div>
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: "var(--muted-2)", marginTop: 7 }}>
          <span>จุดสั่งซื้อ {s.fmt(it.reorder)} {it.unit}</span>
          <span>{pct}% ของจุดสั่งซื้อ</span>
        </div>
      </Card>

      {/* ตัวเลขสำคัญ */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12, marginBottom: 16 }}>
        {[
          { l: "ต้นทุน/หน่วย", v: `฿${s.fmtMoney(it.price)}` },
          { l: "มูลค่าคงเหลือ", v: `฿${s.fmtMoney(value)}` },
          { l: "จำนวนโลเคชั่น", v: `${locs.length} ช่อง` },
          { l: "หน่วยนับ", v: it.unit },
        ].map((x, i) => (
          <div key={i} style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 12, padding: "12px 14px" }}>
            <div style={{ fontSize: 12, color: "var(--muted)" }}>{x.l}</div>
            <div className="num" style={{ fontSize: 17, fontWeight: 600, marginTop: 3 }}>{x.v}</div>
          </div>
        ))}
      </div>

      {/* คงเหลือตามโลเคชั่น (auto-tag) */}
      <SectionHead title="คงเหลือตามโลเคชั่น" sub="แท็กอัตโนมัติจากการรับเข้า/จ่ายออก" />
      <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 22 }}>
        {locs.length === 0 && <Empty icon={<Icons.pin size={22}/>} title="ไม่มีสินค้าในคลัง" />}
        {locs.map(l => (
          <div key={l.code} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 14px", border: "1px solid var(--line)", borderRadius: 12, background: "var(--surface)" }}>
            <span style={{ width: 34, height: 34, borderRadius: 9, background: cat.soft, color: cat.color, display: "grid", placeItems: "center" }}><Icons.pin size={17}/></span>
            <div style={{ flex: 1 }}>
              <div className="num" style={{ fontWeight: 600, fontSize: 14 }}>{l.code}</div>
              <div style={{ fontSize: 11.5, color: "var(--muted-2)" }}>{(s.ZONES.find(z => z.id === l.code[0]) || {}).name}</div>
            </div>
            <div className="num" style={{ fontWeight: 600 }}>{s.fmt(l.qty)} <span style={{ fontSize: 12, color: "var(--muted)", fontWeight: 500 }}>{it.unit}</span></div>
          </div>
        ))}
      </div>

      {/* ประวัติเคลื่อนไหวของสินค้านี้ */}
      <SectionHead title="ประวัติการเคลื่อนไหว" sub={`${moves.length} รายการล่าสุด`} />
      <div style={{ display: "flex", flexDirection: "column" }}>
        {moves.map((m, idx) => {
          const isIn = m.type === "in";
          const line = m.lines.find(l => l.sku === sku);
          return (
            <div className="tl-item" key={m.id}>
              <div className="tl-rail">
                <span className="tl-dot" style={{ background: isIn ? "var(--green-soft)" : "var(--primary-soft)", color: isIn ? "var(--green)" : "var(--primary-700)" }}>
                  {isIn ? <Icons.arrowDown size={15}/> : <Icons.arrowUp size={15}/>}
                </span>
                {idx < moves.length - 1 && <span className="tl-line"></span>}
              </div>
              <div style={{ flex: 1, paddingBottom: 16 }}>
                <div style={{ display: "flex", justifyContent: "space-between" }}>
                  <span style={{ fontWeight: 600, fontSize: 13.5 }}>{isIn ? "รับเข้า" : "จ่ายออก"} · <span className="num">{line.loc}</span></span>
                  <span className="num" style={{ fontWeight: 600, color: isIn ? "var(--green)" : "var(--primary-700)" }}>{isIn ? "+" : "−"}{s.fmt(line.qty)}</span>
                </div>
                <div style={{ fontSize: 12, color: "var(--muted-2)", marginTop: 2 }}>{m.party} · {s.fmtDate(m.date)}</div>
              </div>
            </div>
          );
        })}
      </div>
    </Drawer>
  );
}

function Items({ go, query }) {
  const s = useStore();
  const [cat, setCat] = itUseState("all");
  const [sort, setSort] = itUseState("name");
  const [sel, setSel] = itUseState(null);
  const [q, setQ] = itUseState("");
  const search = (query || q || "").trim().toLowerCase();

  const rows = itUseMemo(() => {
    let r = s.ITEMS.map(i => ({ ...i, qty: s.stockBySku[i.sku] || 0, value: (s.stockBySku[i.sku] || 0) * i.price }));
    if (cat !== "all") r = r.filter(i => i.cat === cat);
    if (search) r = r.filter(i => i.name.toLowerCase().includes(search) || i.sku.toLowerCase().includes(search));
    const sorters = {
      name: (a, b) => a.name.localeCompare(b.name, "th"),
      qty: (a, b) => a.qty - b.qty,
      value: (a, b) => b.value - a.value,
      status: (a, b) => (a.qty / a.reorder) - (b.qty / b.reorder),
    };
    return r.sort(sorters[sort]);
  }, [s.stockBySku, cat, sort, search]);

  return (
    <div className="page fade-up">
      <div className="page-head">
        <h2>ข้อมูลสต๊อกสินค้า</h2>
        <p>รายละเอียดวัสดุแต่ละรายการ · คงเหลือ · มูลค่า · โลเคชั่น</p>
      </div>

      {/* ตัวกรอง */}
      <div style={{ display: "flex", gap: 10, marginBottom: 16, flexWrap: "wrap", alignItems: "center" }}>
        <div className="search" style={{ width: 260 }}>
          <Icons.search size={17}/>
          <input placeholder="ค้นหาชื่อ หรือ รหัสสินค้า…" value={q} onChange={e => setQ(e.target.value)} />
        </div>
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", flex: 1 }}>
          <div className={`chip ${cat === "all" ? "active" : ""}`} onClick={() => setCat("all")}>ทั้งหมด</div>
          {s.CATEGORIES.map(c => (
            <div key={c.id} className={`chip ${cat === c.id ? "active" : ""}`} onClick={() => setCat(c.id)}>
              <span style={{ width: 9, height: 9, borderRadius: 3, background: c.color }}></span>{c.name}
            </div>
          ))}
        </div>
        <select className="select" style={{ width: 170 }} value={sort} onChange={e => setSort(e.target.value)}>
          <option value="name">เรียง: ชื่อ ก-ฮ</option>
          <option value="status">เรียง: สถานะวิกฤต</option>
          <option value="qty">เรียง: คงเหลือน้อย</option>
          <option value="value">เรียง: มูลค่าสูง</option>
        </select>
      </div>

      <Card pad={false}>
        <div className="tbl-wrap">
          <table className="tbl">
            <thead>
              <tr>
                <th>สินค้า</th>
                <th className="t-right">ต้นทุน/หน่วย</th>
                <th className="t-center">โลเคชั่น</th>
                <th className="t-right">คงเหลือ</th>
                <th className="t-right">มูลค่า</th>
                <th>สถานะ</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {rows.map(i => {
                const nLoc = s.locationsOf(i.sku).length;
                return (
                  <tr key={i.sku} style={{ cursor: "pointer" }} onClick={() => setSel(i.sku)}>
                    <td>
                      <div className="item-id">
                        <ItemThumb sku={i.sku} />
                        <div>
                          <div className="item-name">{i.name}</div>
                          <div className="item-sku num">{i.sku}</div>
                        </div>
                      </div>
                    </td>
                    <td className="t-right num">฿{s.fmtMoney(i.price)}</td>
                    <td className="t-center"><span className="badge badge-gray num">{nLoc} ช่อง</span></td>
                    <td className="t-right num" style={{ fontWeight: 600 }}>{s.fmt(i.qty)} <span style={{ color: "var(--muted-2)", fontWeight: 400, fontSize: 12 }}>{i.unit}</span></td>
                    <td className="t-right num" style={{ color: "var(--muted)" }}>฿{s.fmtMoney(i.value)}</td>
                    <td><StockBadge qty={i.qty} reorder={i.reorder} /></td>
                    <td className="t-right"><Icons.chevR size={17} style={{ color: "var(--muted-2)" }}/></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {rows.length === 0 && <Empty icon={<Icons.search size={22}/>} title="ไม่พบสินค้า" sub="ลองเปลี่ยนคำค้นหาหรือหมวด" />}
      </Card>

      {sel && <ItemDrawer sku={sel} onClose={() => setSel(null)} go={go} />}
    </div>
  );
}
window.Items = Items;
