// ============================================================
// reports.jsx — Stock Report + Movement Report
// ============================================================

function ReportsScreen({ state }) {
  const [tab, setTab] = useState("stock");
  const toast = useToast();

  const handleExportCSV = () => {
    const esc = (v) => {
      const s = v == null ? "" : String(v);
      return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
    };
    const toCSV = (headers, rows) =>
      [headers, ...rows].map(r => r.map(esc).join(",")).join("\n");

    let csv = "", filename = "";

    if (tab === "stock") {
      const rows = state.products.flatMap(p => {
        const locs = getLocationsForSKU(state, p.sku);
        return locs.map(l => {
          const loc = state.locations.find(x => x.id === l.locationId);
          const wh = state.warehouses.find(w => w.id === loc?.warehouseId);
          return [p.name, p.sku, p.category, wh?.name || "", l.locationId, l.qty, p.unit, l.qty * p.costPrice];
        });
      });
      csv = toCSV(["สินค้า","SKU","หมวด","คลัง","Location","คงเหลือ","หน่วย","มูลค่า"], rows);
      filename = `stock-report-${new Date().toISOString().slice(0,10)}.csv`;
    } else if (tab === "movement") {
      const rows = state.movements.map(m => {
        const p = state.products.find(x => x.sku === m.sku);
        const u = state.users.find(x => x.id === m.userId);
        return [m.date, m.type, p?.name || m.sku, m.sku, m.locationId, m.ref, u?.name || "", m.qty];
      });
      csv = toCSV(["วันที่","ประเภท","สินค้า","SKU","Location","Ref","ผู้บันทึก","จำนวน"], rows);
      filename = `movement-report-${new Date().toISOString().slice(0,10)}.csv`;
    } else {
      const rows = state.warehouses.map(wh => {
        let value = 0, qty = 0;
        state.locations.filter(l => l.warehouseId === wh.id).forEach(l => {
          Object.entries(state.stock).forEach(([k, q]) => {
            if (k.endsWith("|" + l.id)) {
              const sku = k.split("|")[0];
              const p = state.products.find(x => x.sku === sku);
              value += q * (p?.costPrice || 0);
              qty += q;
            }
          });
        });
        return [wh.name, wh.code, wh.type, wh.temp, qty, value];
      });
      csv = toCSV(["คลัง","รหัส","ประเภท","อุณหภูมิ","หน่วย","มูลค่า"], rows);
      filename = `value-report-${new Date().toISOString().slice(0,10)}.csv`;
    }

    const blob = new Blob(["﻿" + csv], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    toast?.(`ส่งออก ${filename} แล้ว`, "success");
  };

  const handleExportPDF = () => {
    toast?.("กำลังเปิดหน้าต่างพิมพ์ — เลือก Save as PDF", "info");
    document.body.classList.add("printing");
    setTimeout(() => {
      window.print();
      document.body.classList.remove("printing");
    }, 200);
  };

  return (
    <>
      <div className="page-header">
        <div>
          <div className="page-title">รายงาน</div>
          <div className="page-sub">รายงานสต๊อกคงเหลือและความเคลื่อนไหวสินค้า</div>
        </div>
        <div className="row no-print">
          <button className="btn btn-secondary" onClick={handleExportCSV}><Icon name="download" size={13}/> Export CSV</button>
          <button className="btn btn-secondary" onClick={handleExportPDF}><Icon name="download" size={13}/> Export PDF</button>
        </div>
      </div>

      <div className="tabs no-print">
        <button className={`tab ${tab === "stock" ? "active" : ""}`} onClick={() => setTab("stock")}>รายงานสต๊อกคงเหลือ</button>
        <button className={`tab ${tab === "movement" ? "active" : ""}`} onClick={() => setTab("movement")}>รายงานความเคลื่อนไหว</button>
        <button className={`tab ${tab === "value" ? "active" : ""}`} onClick={() => setTab("value")}>รายงานมูลค่า</button>
      </div>

      {tab === "stock" && <StockReport state={state}/>}
      {tab === "movement" && <MovementReport state={state}/>}
      {tab === "value" && <ValueReport state={state}/>}
    </>
  );
}

function StockReport({ state }) {
  const [warehouseId, setWarehouseId] = useState("all");
  const [cat, setCat] = useState("all");

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

  // For each SKU x location matrix
  const rows = state.products.flatMap(p => {
    const locs = getLocationsForSKU(state, p.sku);
    if (locs.length === 0) return [];
    return locs.map(l => {
      const loc = state.locations.find(x => x.id === l.locationId);
      const wh = state.warehouses.find(w => w.id === loc?.warehouseId);
      return { ...p, qty: l.qty, locationId: l.locationId, warehouseId: wh?.id, warehouseName: wh?.name, value: l.qty * p.costPrice };
    });
  }).filter(r => {
    if (warehouseId !== "all" && r.warehouseId !== warehouseId) return false;
    if (cat !== "all" && r.category !== cat) return false;
    return true;
  });

  const totals = {
    qty: rows.reduce((s, r) => s + r.qty, 0),
    value: rows.reduce((s, r) => s + r.value, 0),
    skus: new Set(rows.map(r => r.sku)).size,
  };

  // Category breakdown for donut
  const catBreak = useMemo(() => {
    const tally = {};
    rows.forEach(r => { tally[r.category] = (tally[r.category] || 0) + r.value; });
    const arr = Object.entries(tally).map(([cat, v]) => ({ cat, v })).sort((a, b) => b.v - a.v);
    const total = arr.reduce((s, x) => s + x.v, 0);
    return { arr, total };
  }, [rows]);

  return (
    <>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 360px", gap: 14, marginBottom: 14 }}>
        <div className="card card-pad-0">
          <div className="card-header">
            <h3>สรุปรายคลัง</h3>
          </div>
          <div style={{ padding: 18 }}>
            <WarehouseBreakdownChart state={state} catFilter={cat}/>
          </div>
        </div>
        <div className="card card-pad-0">
          <div className="card-header">
            <h3>สัดส่วนตามหมวด</h3>
            <div className="card-header-sub">มูลค่า {formatCurrency(catBreak.total)}</div>
          </div>
          <div style={{ padding: 18 }}>
            <DonutChart items={catBreak.arr.slice(0, 6)}/>
          </div>
        </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" }}>
          <select className="select" style={{ width: "auto" }} value={warehouseId} onChange={e => setWarehouseId(e.target.value)}>
            <option value="all">ทุกคลัง</option>
            {state.warehouses.map(w => <option key={w.id} value={w.id}>{w.code} · {w.name}</option>)}
          </select>
          <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>
          <div className="spacer"/>
          <div className="text-sm muted">
            {totals.skus} SKU · {formatNumber(totals.qty)} หน่วย · {formatCurrency(totals.value)}
          </div>
        </div>

        <div className="table-wrap">
          <table className="table">
            <thead><tr>
              <th>สินค้า</th><th>SKU</th><th>หมวด</th><th>คลัง</th><th>Location</th><th className="num">คงเหลือ</th><th className="num">มูลค่า</th>
            </tr></thead>
            <tbody>
              {rows.map((r, i) => (
                <tr key={i}>
                  <td>{r.name}</td>
                  <td className="mono text-xs">{r.sku}</td>
                  <td><span className="badge">{r.category}</span></td>
                  <td className="text-xs">{r.warehouseName}</td>
                  <td className="mono text-xs">{r.locationId}</td>
                  <td className="num tnum">{formatNumber(r.qty)} <span className="muted text-xs">{r.unit}</span></td>
                  <td className="num tnum">{formatCurrency(r.value)}</td>
                </tr>
              ))}
              {rows.length === 0 && <tr><td colSpan="7"><EmptyState icon="search" title="ไม่มีข้อมูล"/></td></tr>}
            </tbody>
            <tfoot>
              <tr style={{ fontWeight: 600, background: "var(--surface-2)" }}>
                <td colSpan="5" style={{ padding: 12 }}>รวมทั้งหมด</td>
                <td className="num tnum" style={{ padding: 12 }}>{formatNumber(totals.qty)}</td>
                <td className="num tnum" style={{ padding: 12 }}>{formatCurrency(totals.value)}</td>
              </tr>
            </tfoot>
          </table>
        </div>
      </div>
    </>
  );
}

function MovementReport({ state }) {
  const [type, setType] = useState("all");
  const [days, setDays] = useState(14);
  const [warehouseId, setWarehouseId] = useState("all");

  const cutoff = new Date("2026-05-13T23:59:59"); cutoff.setDate(cutoff.getDate() - days);

  const rows = state.movements.filter(m => {
    if (new Date(m.date) < cutoff) return false;
    if (type !== "all" && m.type !== type) return false;
    if (warehouseId !== "all" && !m.locationId.startsWith(warehouseId)) return false;
    return true;
  });

  const stats = {
    receive: rows.filter(m => m.type === "receive").reduce((s, m) => s + m.qty, 0),
    issue: rows.filter(m => m.type === "issue").reduce((s, m) => s + m.qty, 0),
    txns: rows.length,
  };
  const net = stats.receive - stats.issue;

  // Daily chart
  const chart = useMemo(() => {
    const out = [];
    for (let d = days - 1; d >= 0; d--) {
      const dt = new Date("2026-05-13T23:59:59"); dt.setDate(dt.getDate() - d);
      out.push({ date: dt, key: dt.toISOString().slice(0, 10), receive: 0, issue: 0 });
    }
    rows.forEach(m => {
      const dr = out.find(x => x.key === m.date.slice(0, 10));
      if (dr) dr[m.type] += m.qty;
    });
    return out;
  }, [rows, days]);

  return (
    <>
      <div className="stats-grid" style={{ gridTemplateColumns: "repeat(3, 1fr)" }}>
        <StatCard label="รับเข้า (หน่วย)" value={stats.receive} icon="receive" delta="กลับมาเพิ่มสต๊อก" deltaDir="up"/>
        <StatCard label="จ่ายออก (หน่วย)" value={stats.issue} icon="issue" delta="ออกจากสต๊อก" deltaDir="down"/>
        <StatCard label="ยอดสุทธิ (Net)" value={net} icon="activity" delta={`${stats.txns} รายการ`} deltaDir={net >= 0 ? "up" : "down"}/>
      </div>

      <div className="card card-pad-0" style={{ marginBottom: 14 }}>
        <div className="card-header">
          <h3>กราฟความเคลื่อนไหวรายวัน</h3>
          <div className="row">
            <select className="select" style={{ width: "auto", padding: "5px 10px", fontSize: 12 }} value={days} onChange={e => setDays(Number(e.target.value))}>
              <option value="7">7 วัน</option>
              <option value="14">14 วัน</option>
              <option value="30">30 วัน</option>
            </select>
          </div>
        </div>
        <div style={{ padding: 18 }}>
          <DailyMovementChart data={chart}/>
        </div>
      </div>

      <div className="card card-pad-0">
        <div style={{ padding: 14, display: "flex", gap: 10, alignItems: "center", borderBottom: "1px solid var(--border)" }}>
          <select className="select" style={{ width: "auto" }} value={type} onChange={e => setType(e.target.value)}>
            <option value="all">ทุกประเภท</option>
            <option value="receive">รับเข้า</option>
            <option value="issue">จ่ายออก</option>
          </select>
          <select className="select" style={{ width: "auto" }} value={warehouseId} onChange={e => setWarehouseId(e.target.value)}>
            <option value="all">ทุกคลัง</option>
            {state.warehouses.map(w => <option key={w.id} value={w.id}>{w.code}</option>)}
          </select>
          <div className="spacer"/>
          <div className="text-sm muted">{rows.length} รายการ</div>
        </div>
        <div className="table-wrap" style={{ maxHeight: 480 }}>
          <table className="table">
            <thead><tr>
              <th>วันที่/เวลา</th><th>ประเภท</th><th>สินค้า</th><th>Location</th><th>Ref</th><th>ผู้บันทึก</th><th className="num">จำนวน</th>
            </tr></thead>
            <tbody>
              {rows.slice(0, 200).map(m => {
                const p = state.products.find(x => x.sku === m.sku);
                const u = state.users.find(x => x.id === m.userId);
                return (
                  <tr key={m.id}>
                    <td className="mono text-xs">{formatShortDate(m.date)} {new Date(m.date).toTimeString().slice(0,5)}</td>
                    <td><MovementBadge type={m.type}/></td>
                    <td>
                      <div style={{ fontSize: 13 }}>{p?.name || m.sku}</div>
                      <div className="mono text-xs muted">{m.sku}</div>
                    </td>
                    <td className="mono text-xs">{m.locationId}</td>
                    <td className="mono text-xs">{m.ref}</td>
                    <td className="text-xs">{u?.name || "—"}</td>
                    <td className="num tnum" style={{ fontWeight: 500, color: m.type === "receive" ? "var(--success)" : "var(--danger)" }}>
                      {m.type === "receive" ? "+" : "−"}{formatNumber(m.qty)}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}

function ValueReport({ state }) {
  const byWarehouse = state.warehouses.map(wh => {
    let value = 0; let qty = 0;
    state.locations.filter(l => l.warehouseId === wh.id).forEach(l => {
      Object.entries(state.stock).forEach(([k, q]) => {
        if (k.endsWith("|" + l.id)) {
          const sku = k.split("|")[0];
          const p = state.products.find(x => x.sku === sku);
          value += q * (p?.costPrice || 0);
          qty += q;
        }
      });
    });
    return { ...wh, value, qty };
  });
  const totalValue = byWarehouse.reduce((s, w) => s + w.value, 0);
  const totalQty = byWarehouse.reduce((s, w) => s + w.qty, 0);
  const potentialRevenue = state.products.reduce((s, p) => s + getStockBySKU(state, p.sku) * p.sellPrice, 0);

  return (
    <>
      <div className="stats-grid" style={{ gridTemplateColumns: "repeat(3, 1fr)" }}>
        <StatCard label="มูลค่าสต๊อกรวม (ต้นทุน)" value={totalValue} format="currency" icon="chart" delta={`${formatNumber(totalQty)} หน่วย`} deltaDir=""/>
        <StatCard label="มูลค่าหากจำหน่ายหมด" value={potentialRevenue} format="currency" icon="activity" delta={`+${formatCurrency(potentialRevenue - totalValue)}`} deltaDir="up"/>
        <StatCard label="กำไรประมาณการ" value={potentialRevenue - totalValue} format="currency" icon="package" delta={`${Math.round((potentialRevenue - totalValue) / totalValue * 100)}%`} deltaDir="up"/>
      </div>

      <div className="card card-pad-0">
        <div className="card-header"><h3>มูลค่าสต๊อกแยกตามคลัง</h3></div>
        <div className="table-wrap">
          <table className="table">
            <thead><tr>
              <th>คลัง</th><th>ประเภท</th><th className="num">หน่วย</th><th className="num">มูลค่า</th><th>สัดส่วน</th>
            </tr></thead>
            <tbody>
              {byWarehouse.map(w => (
                <tr key={w.id}>
                  <td>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{w.name}</div>
                    <div className="mono text-xs muted">{w.code}</div>
                  </td>
                  <td className="text-xs">{w.type} · {w.temp}</td>
                  <td className="num tnum">{formatNumber(w.qty)}</td>
                  <td className="num tnum" style={{ fontWeight: 600 }}>{formatCurrency(w.value)}</td>
                  <td style={{ width: 220 }}>
                    <ProgressBar value={(w.value / totalValue) * 100}/>
                    <div className="text-xs muted tnum" style={{ marginTop: 3 }}>{Math.round(w.value / totalValue * 100)}%</div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}

// ============ DailyMovementChart (stacked-style bars) ============
function DailyMovementChart({ data }) {
  const w = 920, h = 220;
  const padL = 36, padR = 12, padT = 12, padB = 28;
  const iw = w - padL - padR;
  const ih = h - padT - padB;
  const maxY = Math.max(50, ...data.flatMap(d => [d.receive, d.issue]));
  const stepX = iw / data.length;
  const yScale = v => padT + ih - (v / maxY) * ih;
  const barW = Math.max(3, stepX * 0.3);

  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height: h }}>
      <g className="chart-grid">
        {[0, 0.25, 0.5, 0.75, 1].map(t => <line key={t} x1={padL} x2={padL + iw} y1={padT + ih * (1-t)} y2={padT + ih * (1-t)}/>)}
      </g>
      <g className="chart-axis">
        {[0, 0.25, 0.5, 0.75, 1].map(t => <text key={t} x={padL - 8} y={padT + ih * (1-t) + 3} textAnchor="end">{Math.round(maxY * t)}</text>)}
        {data.map((d, i) => i % Math.max(1, Math.floor(data.length / 10)) === 0 && (
          <text key={i} x={padL + i * stepX + stepX/2} y={h - 8} textAnchor="middle">{formatShortDate(d.date)}</text>
        ))}
      </g>
      {data.map((d, i) => {
        const cx = padL + i * stepX + stepX / 2;
        const rH = (d.receive / maxY) * ih;
        const iH = (d.issue / maxY) * ih;
        return (
          <g key={i}>
            <rect x={cx - barW} y={padT + ih - rH} width={barW - 1} height={rH} fill="var(--success)" rx="2"
              className="bar-animate" style={{ animationDelay: `${i * 20}ms` }}/>
            <rect x={cx + 1} y={padT + ih - iH} width={barW - 1} height={iH} fill="var(--danger)" rx="2"
              className="bar-animate" style={{ animationDelay: `${i * 20 + 80}ms` }}/>
          </g>
        );
      })}
    </svg>
  );
}

// ============ WarehouseBreakdownChart ============
function WarehouseBreakdownChart({ state, catFilter }) {
  const data = state.warehouses.map(wh => {
    let qty = 0;
    state.locations.filter(l => l.warehouseId === wh.id).forEach(l => {
      Object.entries(state.stock).forEach(([k, q]) => {
        if (k.endsWith("|" + l.id)) {
          const sku = k.split("|")[0];
          const p = state.products.find(x => x.sku === sku);
          if (catFilter === "all" || p?.category === catFilter) qty += q;
        }
      });
    });
    return { ...wh, qty };
  });
  const max = Math.max(1, ...data.map(d => d.qty));
  return (
    <div className="col" style={{ gap: 14 }}>
      {data.map((w, i) => {
        const pct = (w.qty / max) * 100;
        return (
          <div key={w.id}>
            <div className="row" style={{ justifyContent: "space-between", marginBottom: 5 }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{w.name}</div>
                <div className="mono text-xs muted">{w.code} · {w.type}</div>
              </div>
              <span className="tnum" style={{ fontWeight: 600 }}>{formatNumber(w.qty)}</span>
            </div>
            <div style={{ height: 22, background: "var(--surface-2)", borderRadius: 4, overflow: "hidden", position: "relative" }}>
              <div style={{
                width: `${pct}%`, height: "100%",
                background: `linear-gradient(90deg, var(--accent), oklch(0.6 0.18 245))`,
                transition: "width 1.2s cubic-bezier(0.16, 1, 0.3, 1)",
                transitionDelay: `${i * 80}ms`,
              }}/>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ============ DonutChart ============
function DonutChart({ items }) {
  const total = items.reduce((s, x) => s + x.v, 0) || 1;
  const r = 56, cx = 80, cy = 80;
  const stroke = 22;
  const circ = 2 * Math.PI * r;
  let offset = 0;
  const colors = ["#2563eb", "#16a34a", "#d97706", "#7c3aed", "#dc2626", "#0891b2"];

  const [animPct, setAnimPct] = useState(0);
  useEffect(() => {
    const t = setTimeout(() => setAnimPct(1), 60);
    return () => clearTimeout(t);
  }, []);

  return (
    <div className="row" style={{ gap: 16, alignItems: "center" }}>
      <svg viewBox="0 0 160 160" style={{ width: 160, height: 160, flexShrink: 0 }}>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--surface-2)" strokeWidth={stroke}/>
        {items.map((it, i) => {
          const frac = (it.v / total) * animPct;
          const len = frac * circ;
          const dasharray = `${len} ${circ}`;
          const dashoffset = -offset * animPct;
          offset += (it.v / total) * circ;
          return (
            <circle key={it.cat} cx={cx} cy={cy} r={r} fill="none"
              stroke={colors[i % colors.length]} strokeWidth={stroke}
              strokeDasharray={dasharray} strokeDashoffset={dashoffset}
              transform={`rotate(-90 ${cx} ${cy})`}
              style={{ transition: "stroke-dasharray 1.1s ease, stroke-dashoffset 1.1s ease" }}/>
          );
        })}
        <text x={cx} y={cy - 2} textAnchor="middle" style={{ fontSize: 11, fill: "var(--fg-3)" }}>มูลค่ารวม</text>
        <text x={cx} y={cy + 14} textAnchor="middle" style={{ fontSize: 14, fontWeight: 600, fill: "var(--fg)" }}>{formatCurrency(total)}</text>
      </svg>
      <div className="col" style={{ gap: 5, flex: 1 }}>
        {items.map((it, i) => (
          <div key={it.cat} className="row" style={{ justifyContent: "space-between" }}>
            <div className="row" style={{ gap: 7 }}>
              <span style={{ width: 9, height: 9, background: colors[i % colors.length], borderRadius: 2 }}/>
              <span className="text-xs">{it.cat}</span>
            </div>
            <span className="tnum text-xs muted">{Math.round(it.v / total * 100)}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { ReportsScreen });
