// หน้ารายงาน — เคลื่อนไหวสต็อก / คงเหลือ / ประวัติขาย
const SERIAL_CATS = ["เครื่อง", "เครื่องมือสอง", "Notebook/MacBook"];
function ReportsPage({ ui, go }) {
  const { st } = useStore();
  const [tab, setTab] = React.useState("moves");
  const [mvDetail, setMvDetail] = React.useState(null);
  const [mvType, setMvType] = React.useState("ทั้งหมด");
  const [q, setQ] = React.useState("");
  const [printSale, setPrintSale] = React.useState(null);
  const [saleDate, setSaleDate] = React.useState("");
  const [balQ, setBalQ] = React.useState("");
  const [saleQ, setSaleQ] = React.useState("");

  const inBranch = (b) => ui.branch === "ALL" || b === ui.branch;
  const MV_TYPES = ["ทั้งหมด", "รับเข้า", "ขายออก", "โอนย้าย", "ใช้ซ่อม", "ปรับยอด"];
  const tone = (ty) => ty === "ขายออก" ? "danger" : ty === "รับเข้า" ? "ok" : ty === "โอนย้าย" ? "info" : ty === "ใช้ซ่อม" ? "warn" : "muted";

  const moves = st.moves.filter((m) => {
    const p = prodOf(st, m.productId) || { name: "" };
    const locMatch = ui.branch === "ALL" || m.loc.includes(ui.branch);
    return locMatch && (mvType === "ทั้งหมด" || m.type === mvType) && (q === "" || (p.name + m.ref).toLowerCase().includes(q.toLowerCase()));
  });

  const sales = st.sales.filter((s) => inBranch(s.branch));
  const salesByDate0 = saleDate ? sales.filter((s) => { const d = new Date(saleDate); d.setHours(0, 0, 0, 0); return s.ts >= d.getTime() && s.ts < d.getTime() + 86400000; }) : sales;
  const salesByDate = salesByDate0.filter((s) => saleQ.trim() === "" || `${s.id || ""} ${s.customer || ""}`.toLowerCase().includes(saleQ.trim().toLowerCase()));
  const sumSalesByDate = salesByDate.reduce((a, s) => a + saleTotal(s), 0);

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 13 }}>
      <div style={{ display: "flex", gap: 7 }}>
        {[["moves", "รายการเคลื่อนไหว"], ["balance", "ยอดคงเหลือรายสาขา"], ["sales", "ประวัติการขาย"]].map(([v, l]) => (
          <Btn key={v} sm kind={tab === v ? "primary" : "ghost"} onClick={() => setTab(v)}>{l}</Btn>
        ))}
      </div>

      {tab === "moves" && (
        <Card style={{ padding: "14px 18px 8px" }}>
          <div style={{ display: "flex", gap: 8, marginBottom: 10, flexWrap: "wrap", alignItems: "center" }}>
            <div style={{ flex: 1, minWidth: 200 }}><SearchBox value={q} onChange={setQ} placeholder="ค้นหาสินค้า / เลขอ้างอิง…" /></div>
            <div style={{ display: "flex", gap: 5 }}>
              {MV_TYPES.map((ty) => <Btn key={ty} sm kind={mvType === ty ? "primary" : "ghost"} onClick={() => setMvType(ty)}>{ty}</Btn>)}
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "120px 90px 1.5fr 1.2fr 64px 0.8fr 100px", gap: 10, fontSize: 11.5, color: T.sub, fontWeight: 700, padding: "6px 4px 8px", borderBottom: `1px solid ${T.border}` }}>
            <div>เวลา</div><div>ประเภท</div><div>สินค้า</div><div>Location</div><div>จำนวน</div><div>โดย</div><div>อ้างอิง</div>
          </div>
          {moves.slice(0, 40).map((m, i) => {
            const p = prodOf(st, m.productId) || { name: "—" };
            return (
              <div key={m.id} className="ss-row" onClick={() => setMvDetail(m)} style={{ display: "grid", gridTemplateColumns: "120px 90px 1.5fr 1.2fr 64px 0.8fr 100px", gap: 10, alignItems: "center", fontSize: 12.5, padding: "8px 4px", borderBottom: `1px solid ${T.rowBorder}`, cursor: "pointer", animation: `ss-rise .3s ${Math.min(i * 20, 200)}ms ease backwards` }}>
                <div style={{ color: T.sub, fontSize: 11.5 }}>{fmtDT(m.ts)}</div>
                <div><Badge sm tone={tone(m.type)}>{m.type}</Badge></div>
                <div style={{ fontWeight: 600, minWidth: 0, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}{SERIAL_CATS.includes(p.cat) && p.imei ? <span style={{ color: T.sub, fontWeight: 500 }}> · IMEI/SN: {p.imei}</span> : ""}</div>
                <div style={{ fontSize: 11.5, color: T.sub }}>{m.loc.includes("→") ? m.loc : locName(st, m.loc)}</div>
                <div style={{ fontWeight: 800, color: m.qty > 0 ? "#0E7A4D" : T.accent }}>{m.qty > 0 ? "+" : ""}{m.qty}</div>
                <div style={{ fontSize: 11.5 }}>{userOf(st, m.by).name.split(" ")[0]}</div>
                <div style={{ fontSize: 11, fontFamily: "monospace", color: T.primary }}>{m.ref}</div>
              </div>
            );
          })}
          {moves.length === 0 && <EmptyState text="ไม่พบรายการเคลื่อนไหว" />}
        </Card>
      )}

      {tab === "balance" && (
        <Card style={{ padding: "14px 18px 10px" }}>
          <div style={{ marginBottom: 10 }}><SearchBox value={balQ} onChange={setBalQ} placeholder="ค้นหาสินค้า / รุ่น / IMEI / SN…" /></div>
          <div style={{ display: "grid", gridTemplateColumns: `1.7fr repeat(${st.branches.length}, 0.7fr) 0.7fr`, gap: 10, fontSize: 11.5, color: T.sub, fontWeight: 700, padding: "4px 4px 8px", borderBottom: `1px solid ${T.border}` }}>
            <div>สินค้า</div>
            {st.branches.map((b) => <div key={b.id} style={{ textAlign: "center" }}>{b.short}</div>)}
            <div style={{ textAlign: "center" }}>รวม</div>
          </div>
          {st.products.filter((p) => balQ.trim() === "" || `${p.name || ""} ${p.brand || ""} ${p.model || ""} ${p.imei || ""} ${p.sku || ""}`.toLowerCase().includes(balQ.trim().toLowerCase())).map((p, i) => {
            const total = stockTotal(p);
            return (
              <div key={p.id} style={{ display: "grid", gridTemplateColumns: `1.7fr repeat(${st.branches.length}, 0.7fr) 0.7fr`, gap: 10, alignItems: "center", fontSize: 12.5, padding: "7px 4px", borderBottom: `1px solid ${T.rowBorder}`, animation: `ss-rise .3s ${Math.min(i * 20, 200)}ms ease backwards` }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
                  <ProductImg p={p} size={28} radius={7} />
                  <span style={{ fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</span>
                </div>
                {st.branches.map((b) => {
                  const qb = stockInBranch(st, p, b.id);
                  return <div key={b.id} style={{ textAlign: "center", fontWeight: qb > 0 ? 700 : 400, color: qb > 0 ? T.text : "#C2CADB" }}>{qb || "·"}</div>;
                })}
                <div style={{ textAlign: "center", fontFamily: T.headFont, fontWeight: 800, color: total === 0 ? T.accent : total <= p.reorder ? "#B25E09" : T.text }}>{total}</div>
              </div>
            );
          })}
        </Card>
      )}

      {tab === "sales" && (
        <Card style={{ padding: "14px 18px 10px" }}>
          <div style={{ display: "flex", gap: 10, marginBottom: 10, fontSize: 12.5, color: T.sub, alignItems: "center", flexWrap: "wrap" }}>
            <span style={{ fontWeight: 600 }}>เลือกวันที่:</span>
            <input type="date" value={saleDate} onChange={(e) => setSaleDate(e.target.value)} style={{ padding: "8px 12px", border: `1px solid ${T.border}`, borderRadius: 10, fontFamily: T.bodyFont, fontSize: 13, color: T.text, cursor: "pointer" }} />
            {saleDate ? <Btn sm kind="ghost" onClick={() => setSaleDate("")}>✕ ดูทั้งหมด</Btn> : <span style={{ fontSize: 11.5 }}>(ว่าง = ดูทุกวัน)</span>}
            <div style={{ flex: 1, minWidth: 180 }}><SearchBox value={saleQ} onChange={setSaleQ} placeholder="ค้นหาเลขที่ INV / ลูกค้า…" /></div>
            <div style={{ marginLeft: "auto", display: "flex", gap: 16 }}>
              <span>{saleDate ? "วันนี้" : "ทั้งหมด"} <b style={{ color: T.text }}>{salesByDate.length}</b> บิล</span>
              <span>ยอดรวม <b style={{ color: T.text }}>{fmtMoney(sumSalesByDate)}</b></span>
            </div>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "120px 110px 1.4fr 0.9fr 0.8fr 100px auto", gap: 10, fontSize: 11.5, color: T.sub, fontWeight: 700, padding: "4px 4px 8px", borderBottom: `1px solid ${T.border}` }}>
            <div>เลขที่</div><div>เวลา</div><div>ลูกค้า</div><div>สาขา / พนักงาน</div><div>ชำระโดย</div><div>ยอดสุทธิ</div><div></div>
          </div>
          {salesByDate.map((s, i) => (
            <div key={s.id} style={{ display: "grid", gridTemplateColumns: "120px 110px 1.4fr 0.9fr 0.8fr 100px auto", gap: 10, alignItems: "center", fontSize: 12.5, padding: "8px 4px", borderBottom: `1px solid ${T.rowBorder}`, animation: `ss-rise .3s ${Math.min(i * 20, 200)}ms ease backwards` }}>
              <div style={{ fontWeight: 700, color: T.primary, fontSize: 12 }}>{s.id}</div>
              <div style={{ color: T.sub, fontSize: 11.5 }}>{fmtDT(s.ts)}</div>
              <div style={{ minWidth: 0, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{s.customer} <span style={{ color: T.sub, fontSize: 11 }}>· {s.items.length} รายการ</span></div>
              <div style={{ fontSize: 11.5, color: T.sub }}>{branchOf(st, s.branch).short} · {userOf(st, s.by).name.split(" ")[0]}</div>
              <div style={{ fontSize: 11.5 }}><Badge sm tone="muted">{s.pay}</Badge></div>
              <div style={{ fontWeight: 800 }}>{fmtMoney(saleTotal(s))}</div>
              <Btn sm kind="ghost" onClick={() => setPrintSale(s)}>⎙ ใบเสร็จ</Btn>
            </div>
          ))}
          {salesByDate.length === 0 && <EmptyState text={saleDate ? "ไม่มีบิลขายในวันที่เลือก" : "ยังไม่มีประวัติการขาย"} />}
        </Card>
      )}

      {/* ── รายละเอียดรายการเคลื่อนไหว ── */}
      <Modal open={!!mvDetail} onClose={() => setMvDetail(null)} width={460}
        title={mvDetail ? `รายการเคลื่อนไหว · ${mvDetail.type}` : ""}
        footer={mvDetail && <React.Fragment>
          {(() => {
            const ref = mvDetail.ref || "";
            if (/^INV-/.test(ref)) { const s = st.sales.find((x) => x.id === ref); if (s) return <Btn kind="soft" style={{ marginRight: "auto" }} onClick={() => { setMvDetail(null); setPrintSale(s); }}>ดูใบเสร็จ {ref}</Btn>; }
            if (/^RP-/.test(ref)) return <Btn kind="soft" style={{ marginRight: "auto" }} onClick={() => { setMvDetail(null); go("repairs", ref); }}>ไปดูงานซ่อม {ref}</Btn>;
            if (/^BI-/.test(ref)) return <Btn kind="soft" style={{ marginRight: "auto" }} onClick={() => { setMvDetail(null); go("buyin"); }}>ไปหน้ารับซื้อ</Btn>;
            return null;
          })()}
          <Btn kind="ghost" onClick={() => setMvDetail(null)}>ปิด</Btn>
        </React.Fragment>}>
        {mvDetail && (() => {
          const p = prodOf(st, mvDetail.productId) || { name: "(สินค้าถูกลบ)", sku: "", cat: "" };
          const sale = /^INV-/.test(mvDetail.ref || "") ? st.sales.find((x) => x.id === mvDetail.ref) : null;
          const Row = ({ label, children }) => (
            <div style={{ display: "flex", gap: 10, fontSize: 13, padding: "8px 0", borderBottom: `1px solid ${T.rowBorder}`, alignItems: "baseline" }}>
              <span style={{ color: T.sub, minWidth: 120, fontWeight: 600 }}>{label}</span>
              <span style={{ flex: 1, fontWeight: 600, wordBreak: "break-word" }}>{children}</span>
            </div>
          );
          return (
            <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
              <div style={{ display: "flex", gap: 12, alignItems: "center", marginBottom: 8 }}>
                <ProductImg p={p} size={48} radius={11} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontFamily: T.headFont, fontWeight: 800, fontSize: 16 }}>{p.name}{SERIAL_CATS.includes(p.cat) && p.imei ? <span style={{ color: T.sub, fontWeight: 600, fontSize: 13 }}> · IMEI/SN: {p.imei}</span> : ""}</div>
                  {p.sku && <div style={{ fontSize: 11.5, color: T.sub, fontFamily: "monospace" }}>{p.sku}</div>}
                </div>
                <div style={{ marginLeft: "auto" }}><Badge tone={tone(mvDetail.type)}>{mvDetail.type}</Badge></div>
              </div>
              <Row label="เวลา">{fmtDT(mvDetail.ts)}</Row>
              <Row label="จำนวน"><span style={{ fontWeight: 800, color: mvDetail.qty > 0 ? "#0E7A4D" : T.accent }}>{mvDetail.qty > 0 ? "+" : ""}{mvDetail.qty}</span></Row>
              <Row label="Location">{mvDetail.loc.includes("→") ? mvDetail.loc : locName(st, mvDetail.loc)}</Row>
              <Row label="หมวดสินค้า">{p.cat || "—"}</Row>
              <Row label="ผู้ทำรายการ">{userOf(st, mvDetail.by).name}</Row>
              <Row label="เลขอ้างอิง"><span style={{ fontFamily: "monospace", color: T.primary }}>{mvDetail.ref}</span></Row>
              {sale && (
                <div style={{ marginTop: 10, background: T.chipBg, borderRadius: 10, padding: "10px 14px", fontSize: 12.5 }}>
                  <div style={{ fontWeight: 700, marginBottom: 4 }}>บิลขาย {sale.id}</div>
                  <div style={{ color: T.sub }}>ลูกค้า: {sale.customer} · {sale.items.length} รายการ · ชำระ {sale.pay}</div>
                  <div style={{ color: T.sub }}>ยอดสุทธิ: <b style={{ color: T.text }}>{fmtMoney(saleTotal(sale))}</b></div>
                </div>
              )}
            </div>
          );
        })()}
      </Modal>

      <PrintModal open={!!printSale} onClose={() => setPrintSale(null)} kind="sale" data={printSale} />
    </div>
  );
}
window.ReportsPage = ReportsPage;
