// reports.jsx — Reports: Stock report + Movement report

const { useState: useState_rp, useMemo: useMemo_rp } = React;

function ReportsScreen() {
  const [tab, setTab] = useState_rp("stock");
  return (
    <div className="col gap-md">
      <div style={{display:"flex", alignItems:"center", gap:14}}>
        <div className="tabs">
          <div className={"tab " + (tab === "stock" ? "active" : "")} onClick={() => setTab("stock")}>รายงานสต๊อกคงเหลือ</div>
          <div className={"tab " + (tab === "movement" ? "active" : "")} onClick={() => setTab("movement")}>รายงานการเคลื่อนไหว</div>
          <div className={"tab " + (tab === "valuation" ? "active" : "")} onClick={() => setTab("valuation")}>รายงานมูลค่า</div>
        </div>
        <div className="grow"/>
        <button className="btn"><Icon name="filter" size={13}/>กรองข้อมูล</button>
        <button className="btn primary"><Icon name="download" size={13}/>Export CSV</button>
      </div>
      {tab === "stock" && <StockReport/>}
      {tab === "movement" && <MovementReport/>}
      {tab === "valuation" && <ValuationReport/>}
    </div>
  );
}

function StockReport() {
  const { items, locations, stock, getStock, totalQty } = useStore();
  const [locFilter, setLocFilter] = useState_rp("all");
  const [query, setQuery] = useState_rp("");

  const filtered = items.filter(it => {
    if (query && !(it.name.toLowerCase().includes(query.toLowerCase()) || it.sku.toLowerCase().includes(query.toLowerCase()))) return false;
    return true;
  });

  const totals = useMemo_rp(() => {
    let units = 0, value = 0;
    filtered.forEach(it => {
      const q = locFilter === "all" ? totalQty(it.sku) : getStock(it.sku, locFilter);
      units += q;
      value += q * it.cost;
    });
    return { units, value };
  }, [filtered, locFilter, getStock, totalQty]);

  return (
    <div className="col gap-md">
      {/* Summary tiles */}
      <div style={{display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:14}}>
        <ReportTile label="SKU ทั้งหมด" value={fmtNum(filtered.length)} ico="package" color="#6d7cff"/>
        <ReportTile label="หน่วยรวม" value={fmtNum(totals.units)} ico="warehouse" color="#38d3a3"/>
        <ReportTile label="มูลค่าต้นทุน" value={fmtMoney(totals.value)} ico="trend-up" color="#ffb454"/>
        <ReportTile label="ใกล้หมด" value={fmtNum(filtered.filter(it => totalQty(it.sku) < it.reorder).length)} ico="alert" color="#ff6b78"/>
      </div>

      <div className="card">
        <div className="card-head">
          <div className="card-title">สต๊อกคงเหลือ — รายงาน</div>
          <div className="card-sub">ณ {new Date().toLocaleDateString("th-TH", { day:"2-digit", month:"long", year:"numeric" })}</div>
          <select className="select" style={{width:200, marginLeft:"auto"}} value={locFilter} onChange={e => setLocFilter(e.target.value)}>
            <option value="all">ทุกที่จัดเก็บ</option>
            {locations.map(l => <option key={l.id} value={l.id}>{l.name}</option>)}
          </select>
          <div className="search" style={{width:200}}>
            <Icon name="search" size={14}/>
            <input placeholder="ค้นหา..." value={query} onChange={e => setQuery(e.target.value)}/>
          </div>
        </div>
        <div className="table-wrap" style={{maxHeight: "calc(100vh - 420px)"}}>
          <table className="tbl">
            <thead>
              <tr>
                <th style={{width:100}}>SKU</th>
                <th>ชื่อสินค้า</th>
                <th>หมวด</th>
                {locFilter === "all" ? locations.map(l => <th key={l.id} style={{textAlign:"right"}}>{l.id}</th>) : <th style={{textAlign:"right"}}>{locations.find(l => l.id === locFilter)?.name}</th>}
                <th style={{textAlign:"right", borderLeft:"1px solid var(--border)"}}>รวม</th>
                <th style={{textAlign:"right"}}>มูลค่าต้นทุน</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(it => {
                const total = locFilter === "all" ? totalQty(it.sku) : getStock(it.sku, locFilter);
                const value = total * it.cost;
                const low = total < it.reorder;
                return (
                  <tr key={it.sku}>
                    <td className="cell-sku">{it.sku}</td>
                    <td>
                      <div style={{fontWeight:500}}>{it.name}</div>
                      {low && <div className="chip err" style={{marginTop:3, fontSize:10.5}}><Icon name="alert" size={10}/>ต่ำกว่า Reorder</div>}
                    </td>
                    <td><span className="cat-chip">{it.category}</span></td>
                    {locFilter === "all" ? locations.map(l => {
                      const q = getStock(it.sku, l.id);
                      return <td key={l.id} className="cell-num num" style={{opacity: q === 0 ? 0.3 : 1}}>{q ? fmtNum(q) : "—"}</td>;
                    }) : (
                      <td className="cell-num num">{total ? fmtNum(total) : "—"}</td>
                    )}
                    <td className="cell-num num" style={{fontWeight:700, borderLeft:"1px solid var(--border)"}}>{fmtNum(total)}</td>
                    <td className="cell-num num muted">{fmtMoney(value)}</td>
                  </tr>
                );
              })}
            </tbody>
            <tfoot>
              <tr style={{background:"rgba(255,255,255,0.03)"}}>
                <td colSpan={locFilter === "all" ? 3 + locations.length : 4} style={{padding:"12px 14px", fontWeight:700}}>รวมทั้งสิ้น</td>
                <td className="cell-num num" style={{fontWeight:700, fontSize:14, borderLeft:"1px solid var(--border)"}}>{fmtNum(totals.units)}</td>
                <td className="cell-num num" style={{fontWeight:700, fontSize:14}}>{fmtMoney(totals.value)}</td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
    </div>
  );
}

function MovementReport() {
  const { movements, items, locations } = useStore();
  const [type, setType] = useState_rp("all");
  const [range, setRange] = useState_rp(30);
  const [query, setQuery] = useState_rp("");

  const filtered = movements.filter(m => {
    if (type !== "all" && m.type !== type) return false;
    if (range && (Date.now() - m.ts) > range * 86400000) return false;
    if (query) {
      const q = query.toLowerCase();
      return m.itemName.toLowerCase().includes(q) || m.sku.toLowerCase().includes(q) || m.ref.toLowerCase().includes(q) || m.id.toLowerCase().includes(q);
    }
    return true;
  });

  const summary = useMemo_rp(() => {
    const inQty = filtered.filter(m => m.type === "IN").reduce((a, b) => a + b.qty, 0);
    const outQty = filtered.filter(m => m.type === "OUT").reduce((a, b) => a + b.qty, 0);
    const xferQty = filtered.filter(m => m.type === "XFER").reduce((a, b) => a + b.qty, 0);
    return { inQty, outQty, xferQty, total: filtered.length };
  }, [filtered]);

  // Daily flow chart
  const flow = useMemo_rp(() => {
    const days = [];
    for (let i = Math.min(range, 30) - 1; i >= 0; i--) {
      const d = new Date(); d.setHours(0,0,0,0); d.setDate(d.getDate() - i);
      const start = d.getTime(), end = start + 86400000;
      const day = filtered.filter(m => m.ts >= start && m.ts < end);
      days.push({
        label: d.getDate(),
        in: day.filter(m => m.type === "IN").reduce((a,b) => a+b.qty, 0),
        out: day.filter(m => m.type === "OUT").reduce((a,b) => a+b.qty, 0),
      });
    }
    return days;
  }, [filtered, range]);

  return (
    <div className="col gap-md">
      <div style={{display:"grid", gridTemplateColumns:"repeat(4, 1fr)", gap:14}}>
        <ReportTile label="รายการเคลื่อนไหว" value={fmtNum(summary.total)} ico="history" color="#6d7cff"/>
        <ReportTile label="หน่วยรับเข้า" value={fmtNum(summary.inQty)} ico="in" color="#38d3a3"/>
        <ReportTile label="หน่วยจ่ายออก" value={fmtNum(summary.outQty)} ico="out" color="#ff6b78"/>
        <ReportTile label="หน่วยโอนระหว่างคลัง" value={fmtNum(summary.xferQty)} ico="transfer" color="#5fb8ff"/>
      </div>

      <div className="card">
        <div className="card-head">
          <div className="card-title">การเคลื่อนไหวรายวัน</div>
          <div className="card-sub">{range} วันล่าสุด</div>
          <div style={{marginLeft:"auto", display:"flex", gap:14, fontSize: 12}}>
            <span style={{display:"inline-flex", alignItems:"center", gap:6}}><span style={{width:10, height:10, borderRadius:3, background:"var(--accent-2)"}}/><span className="muted">เข้า</span></span>
            <span style={{display:"inline-flex", alignItems:"center", gap:6}}><span style={{width:10, height:10, borderRadius:3, background:"#ff8089"}}/><span className="muted">ออก</span></span>
          </div>
        </div>
        <div style={{padding:"12px 18px 18px"}}>
          <BarChart data={flow} height={180}/>
        </div>
      </div>

      <div className="card">
        <div className="card-head">
          <div className="card-title">รายการเคลื่อนไหวทั้งหมด</div>
          <div className="card-sub">{filtered.length} รายการ</div>
          <div className="tabs" style={{marginLeft:"auto"}}>
            <div className={"tab " + (type === "all" ? "active" : "")} onClick={() => setType("all")}>ทั้งหมด</div>
            <div className={"tab " + (type === "IN" ? "active" : "")} onClick={() => setType("IN")}>เข้า</div>
            <div className={"tab " + (type === "OUT" ? "active" : "")} onClick={() => setType("OUT")}>ออก</div>
            <div className={"tab " + (type === "XFER" ? "active" : "")} onClick={() => setType("XFER")}>โอน</div>
          </div>
          <select className="select" style={{width:130}} value={range} onChange={e => setRange(+e.target.value)}>
            <option value={7}>7 วัน</option>
            <option value={30}>30 วัน</option>
            <option value={90}>90 วัน</option>
          </select>
          <div className="search" style={{width:200}}>
            <Icon name="search" size={14}/>
            <input placeholder="ค้นหา..." value={query} onChange={e => setQuery(e.target.value)}/>
          </div>
        </div>
        <div className="table-wrap" style={{maxHeight: "calc(100vh - 540px)"}}>
          <table className="tbl">
            <thead>
              <tr>
                <th style={{width:100}}>วันที่</th>
                <th style={{width:80}}>ประเภท</th>
                <th style={{width:110}}>เลขที่</th>
                <th>สินค้า</th>
                <th>จาก → ถึง</th>
                <th style={{width:120}}>อ้างอิง</th>
                <th style={{width:100, textAlign:"right"}}>จำนวน</th>
                <th style={{width:90}}>ผู้ทำรายการ</th>
              </tr>
            </thead>
            <tbody>
              {filtered.slice(0, 80).map(m => {
                const it = items.find(i => i.sku === m.sku);
                return (
                  <tr key={m.id}>
                    <td><span className="num muted" style={{fontSize:11.5}}>{fmtDateTime(m.ts)}</span></td>
                    <td><span className={"mv-type " + m.type}>{m.type === "IN" ? "รับเข้า" : m.type === "OUT" ? "จ่ายออก" : "โอน"}</span></td>
                    <td className="cell-sku">{m.id}</td>
                    <td>
                      <div style={{fontSize:13, fontWeight:500, maxWidth:240, overflow:"hidden", textOverflow:"ellipsis", whiteSpace:"nowrap"}}>{m.itemName}</div>
                      <div className="muted mono" style={{fontSize:10.5, marginTop:2}}>{m.sku}</div>
                    </td>
                    <td>
                      <div style={{fontSize:12.5, display:"flex", alignItems:"center", gap:6}}>
                        <span className="mono muted">{m.fromLoc || "—"}</span>
                        <Icon name="arrow-right" size={11} style={{opacity:0.5}}/>
                        <span className="mono">{m.toLoc || "—"}</span>
                      </div>
                    </td>
                    <td><span style={{fontSize:12}}>{m.ref}</span></td>
                    <td className="cell-num">
                      <span className="num" style={{fontWeight:700, color: m.type === "OUT" ? "var(--danger)" : m.type === "IN" ? "var(--ok)" : "var(--info)"}}>
                        {m.type === "OUT" ? "−" : m.type === "IN" ? "+" : "±"}{fmtNum(m.qty)}
                      </span>
                      {it && <div className="muted" style={{fontSize:10.5, marginTop:1}}>{it.unit}</div>}
                    </td>
                    <td><span style={{fontSize:12}}>{m.user}</span></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function ValuationReport() {
  const { items, locations, totalQty, getStock } = useStore();

  const byCategory = useMemo_rp(() => {
    const m = new Map();
    items.forEach(it => {
      const q = totalQty(it.sku);
      const v = q * it.cost;
      m.set(it.category, (m.get(it.category) || 0) + v);
    });
    const colors = { Electronics: "#6d7cff", Apparel: "#38d3a3", Grocery: "#ffb454", Household: "#5fb8ff", Stationery: "#c084fc" };
    return [...m.entries()].map(([k, v]) => ({ label: k, value: Math.round(v), color: colors[k] || "#888" })).sort((a,b) => b.value - a.value);
  }, [items, totalQty]);

  const byLocation = useMemo_rp(() => {
    return locations.map(l => {
      let v = 0;
      items.forEach(it => v += getStock(it.sku, l.id) * it.cost);
      return { ...l, value: Math.round(v) };
    }).sort((a,b) => b.value - a.value);
  }, [locations, items, getStock]);

  const totalValue = byCategory.reduce((a,b) => a + b.value, 0);

  return (
    <div className="col gap-md">
      <div style={{display:"grid", gridTemplateColumns:"1fr 1fr", gap:14}}>
        <div className="card">
          <div className="card-head">
            <div>
              <div className="card-title">มูลค่าสต๊อกแยกตามหมวด</div>
              <div className="card-sub">ต้นทุนรวม {fmtMoney(totalValue)}</div>
            </div>
          </div>
          <div style={{padding:"20px 18px 24px", display:"flex", gap:24, alignItems:"center"}}>
            <Donut segments={byCategory} size={180} thickness={24}/>
            <div style={{flex:1, display:"flex", flexDirection:"column", gap:10}}>
              {byCategory.map(c => (
                <div key={c.label}>
                  <div style={{display:"flex", alignItems:"baseline", marginBottom:4}}>
                    <span style={{width:10, height:10, borderRadius:3, background:c.color, marginRight:8}}/>
                    <span style={{fontSize:13, fontWeight:500}}>{c.label}</span>
                    <span className="num muted" style={{marginLeft:"auto", fontSize:13}}>{fmtMoney(c.value)}</span>
                  </div>
                  <div className="pbar"><span style={{width: ((c.value/totalValue)*100)+"%", background: c.color}}/></div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <div>
              <div className="card-title">มูลค่าสต๊อกแยกตามที่จัดเก็บ</div>
              <div className="card-sub">เรียงจากมากไปน้อย</div>
            </div>
          </div>
          <div style={{padding:"10px 14px 14px"}}>
            {byLocation.map(l => (
              <div key={l.id} style={{padding:"10px 8px", display:"flex", alignItems:"center", gap:12, borderBottom:"1px solid rgba(255,255,255,0.04)"}}>
                <div className={"loc-icon " + (l.type === "shop" ? "shop" : l.type === "qc" ? "qc" : "")} style={{width:32, height:32}}>
                  <Icon name={l.type === "shop" ? "store" : l.type === "qc" ? "qc" : "warehouse"} size={16}/>
                </div>
                <div style={{flex:1}}>
                  <div style={{fontSize:13, fontWeight:500}}>{l.name}</div>
                  <div className="muted" style={{fontSize:11, marginTop:2}}><span className="mono">{l.id}</span></div>
                </div>
                <div style={{textAlign:"right"}}>
                  <div className="num" style={{fontWeight:700, fontSize:14}}>{fmtMoney(l.value)}</div>
                  <div className="muted" style={{fontSize:10.5, marginTop:1}}>{((l.value/totalValue)*100).toFixed(1)}%</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="card">
        <div className="card-head">
          <div className="card-title">รายการมูลค่าสต๊อกทุกรายการ</div>
          <div className="card-sub">เรียงจากมูลค่ามากไปน้อย</div>
        </div>
        <div className="table-wrap" style={{maxHeight: 420}}>
          <table className="tbl">
            <thead>
              <tr>
                <th>SKU</th>
                <th>ชื่อสินค้า</th>
                <th>หมวด</th>
                <th style={{textAlign:"right"}}>คงเหลือ</th>
                <th style={{textAlign:"right"}}>ต้นทุน/หน่วย</th>
                <th style={{textAlign:"right"}}>มูลค่าต้นทุน</th>
                <th style={{textAlign:"right"}}>ราคาขาย/หน่วย</th>
                <th style={{textAlign:"right"}}>มูลค่าขาย</th>
              </tr>
            </thead>
            <tbody>
              {[...items].map(it => ({ ...it, q: totalQty(it.sku) })).sort((a,b) => b.q*b.cost - a.q*a.cost).map(it => (
                <tr key={it.sku}>
                  <td className="cell-sku">{it.sku}</td>
                  <td><div style={{fontWeight:500}}>{it.name}</div></td>
                  <td><span className="cat-chip">{it.category}</span></td>
                  <td className="cell-num num">{fmtNum(it.q)}</td>
                  <td className="cell-num num muted">{fmtMoney(it.cost)}</td>
                  <td className="cell-num num" style={{fontWeight:600}}>{fmtMoney(it.q * it.cost)}</td>
                  <td className="cell-num num muted">{fmtMoney(it.price)}</td>
                  <td className="cell-num num" style={{fontWeight:600, color:"var(--ok)"}}>{fmtMoney(it.q * it.price)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function ReportTile({ label, value, ico, color }) {
  return (
    <div className="card pad" style={{position:"relative", overflow:"hidden"}}>
      <div style={{position:"absolute", right:-30, top:-30, width:120, height:120, borderRadius:"50%", background:`radial-gradient(circle, ${color}30 0%, transparent 65%)`, filter:"blur(4px)"}}/>
      <div style={{display:"flex", alignItems:"center", gap:8, color:"var(--text-mute)", fontSize:12}}>
        <span style={{width:24, height:24, borderRadius:7, background:`${color}22`, color, display:"grid", placeItems:"center"}}><Icon name={ico} size={13}/></span>
        {label}
      </div>
      <div className="num" style={{fontSize:22, fontWeight:700, marginTop:6}}>{value}</div>
    </div>
  );
}

Object.assign(window, { ReportsScreen });
