// ==========================================
// Reports — Stock balance / Movement / Transfer
// ==========================================

function ReportsPage({ state }) {
  const [tab, setTab] = useState("balance");
  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1>รายงาน</h1>
          <p className="muted">รายงานคงเหลือ การเคลื่อนไหว และการโอนย้ายระหว่างหน่วยงาน</p>
        </div>
        <button className="btn-ghost" onClick={() => window.print()}>🖨 พิมพ์รายงาน</button>
      </div>

      <div className="tab-bar">
        <button className={`tab ${tab === "balance" ? "active" : ""}`} onClick={() => setTab("balance")}>📊 วัสดุคงเหลือ</button>
        <button className={`tab ${tab === "move" ? "active" : ""}`} onClick={() => setTab("move")}>🔁 การเคลื่อนไหว</button>
        <button className={`tab ${tab === "transfer" ? "active" : ""}`} onClick={() => setTab("transfer")}>↔️ การโอนย้าย</button>
      </div>

      {tab === "balance" && <BalanceReport state={state} />}
      {tab === "move" && <MovementReport state={state} />}
      {tab === "transfer" && <TransferReport state={state} />}
    </div>
  );
}

// -------- 1) Balance --------
function BalanceReport({ state }) {
  const stock = useMemo(() => computeStock(state), [state]);
  const [catFilter, setCatFilter] = useState("all");
  const [projFilter, setProjFilter] = useState("all");
  const catMap = Object.fromEntries(state.categories.map((c) => [c.id, c]));

  const rows = state.materials
    .filter((m) => catFilter === "all" || m.category === catFilter)
    .map((m) => {
      const perProj = state.projects.map((p) => ({ p, qty: stock[m.id]?.[p.id] || 0 }));
      const total = perProj.reduce((a, b) => a + b.qty, 0);
      return { m, perProj, total };
    });

  // category breakdown
  const catSummary = state.categories.map((c) => {
    const items = state.materials.filter((m) => m.category === c.id);
    const total = items.reduce((a, m) => a + materialTotal(stock, m.id), 0);
    return { ...c, total };
  });

  return (
    <>
      <div className="grid-2">
        <div className="card">
          <div className="card-head"><h3>สัดส่วนวัสดุคงเหลือตามหมวด</h3></div>
          <div style={{ display: "flex", alignItems: "center", gap: 24 }}>
            <Donut slices={catSummary.map((c) => ({ v: c.total, color: c.color }))} />
            <div style={{ flex: 1 }}>
              {catSummary.map((c) => (
                <div key={c.id} className="legend-row">
                  <span className="legend-dot" style={{ background: c.color }} />
                  <span style={{ flex: 1 }}>{c.icon} {c.name}</span>
                  <b>{fmtNum(c.total)}</b>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-head"><h3>สรุปตามหน่วยงาน</h3></div>
          <table className="data-table compact">
            <thead><tr><th>หน่วยงาน</th><th className="num-col">รายการ</th><th className="num-col">ปริมาณรวม</th></tr></thead>
            <tbody>
              {state.projects.map((p) => {
                const items = state.materials.filter((m) => (stock[m.id]?.[p.id] || 0) > 0);
                const total = items.reduce((a, m) => a + (stock[m.id]?.[p.id] || 0), 0);
                return (
                  <tr key={p.id}>
                    <td><b>{p.name}</b><div className="muted small">{p.code}</div></td>
                    <td className="num-col">{fmtNum(items.length)}</td>
                    <td className="num-col"><b>{fmtNum(total)}</b></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      <div className="filter-bar">
        <div className="chip-group">
          <button className={`chip ${catFilter === "all" ? "active" : ""}`} onClick={() => setCatFilter("all")}>ทั้งหมด</button>
          {state.categories.map((c) => (
            <button key={c.id} className={`chip ${catFilter === c.id ? "active" : ""}`} onClick={() => setCatFilter(c.id)} style={catFilter === c.id ? { background: c.color, borderColor: c.color, color: "#fff" } : {}}>{c.icon} {c.name}</button>
          ))}
        </div>
        <div className="filter-right">
          <select value={projFilter} onChange={(e) => setProjFilter(e.target.value)}>
            <option value="all">ทุกหน่วยงาน</option>
            {state.projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
          <button className="btn-ghost" onClick={() => exportCSV("balance", state, stock, catFilter, projFilter)}>⬇ CSV</button>
        </div>
      </div>

      <div className="card no-pad">
        <table className="data-table">
          <thead>
            <tr>
              <th>รหัส</th>
              <th>วัสดุ</th>
              <th>หมวด</th>
              <th>หน่วย</th>
              {state.projects.map((p) => <th key={p.id} className="num-col">{p.code}</th>)}
              <th className="num-col">รวม</th>
              <th className="num-col">ขั้นต่ำ</th>
              <th>สถานะ</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(({ m, perProj, total }) => (
              <tr key={m.id}>
                <td className="mono">{m.id}</td>
                <td><b>{m.name}</b></td>
                <td><CatBadge cat={catMap[m.category]} /></td>
                <td>{m.unit}</td>
                {perProj.map(({ p, qty }) => (
                  <td key={p.id} className="num-col" style={{ color: qty <= 0 ? "#bbb" : "#111" }}>{fmtNum(qty)}</td>
                ))}
                <td className="num-col"><b>{fmtNum(total)}</b></td>
                <td className="num-col muted">{fmtNum(m.min)}</td>
                <td>
                  {total <= 0 ? <span className="status-pill" style={{ background: "#fbe6e6", color: "#a32424" }}>หมด</span>
                    : total < m.min ? <span className="status-pill" style={{ background: "#fef3d6", color: "#8a6300" }}>ต่ำ</span>
                    : <span className="status-pill" style={{ background: "#e1f3e8", color: "#1F8A5B" }}>ปกติ</span>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

// -------- 2) Movement (เคลื่อนไหว) --------
function MovementReport({ state }) {
  const [from, setFrom] = useState(() => {
    const d = new Date(); d.setDate(d.getDate() - 30); return d.toISOString().slice(0, 10);
  });
  const [to, setTo] = useState(() => new Date().toISOString().slice(0, 10));
  const [catFilter, setCatFilter] = useState("all");
  const [projFilter, setProjFilter] = useState("all");
  const [typeFilter, setTypeFilter] = useState("all");

  const matMap = Object.fromEntries(state.materials.map((m) => [m.id, m]));
  const projMap = Object.fromEntries(state.projects.map((p) => [p.id, p]));
  const catMap = Object.fromEntries(state.categories.map((c) => [c.id, c]));

  const rows = state.transactions
    .filter((t) => {
      const d = new Date(t.date);
      if (d < new Date(from + "T00:00") || d > new Date(to + "T23:59")) return false;
      if (typeFilter !== "all" && t.type !== typeFilter) return false;
      const m = matMap[t.materialId];
      if (catFilter !== "all" && m?.category !== catFilter) return false;
      if (projFilter !== "all") {
        if (t.type === "transfer") {
          if (t.fromProjectId !== projFilter && t.toProjectId !== projFilter) return false;
        } else if (t.projectId !== projFilter) return false;
      }
      return true;
    })
    .sort((a, b) => new Date(b.date) - new Date(a.date));

  const sums = {
    receive: rows.filter((t) => t.type === "receive").reduce((a, t) => a + t.qty, 0),
    issue: rows.filter((t) => t.type === "issue").reduce((a, t) => a + t.qty, 0),
    transfer: rows.filter((t) => t.type === "transfer").reduce((a, t) => a + t.qty, 0),
  };

  return (
    <>
      <div className="filter-bar">
        <div className="filter-left">
          <label>ตั้งแต่ <input type="date" value={from} onChange={(e) => setFrom(e.target.value)} /></label>
          <label>ถึง <input type="date" value={to} onChange={(e) => setTo(e.target.value)} /></label>
        </div>
        <div className="filter-right">
          <select value={typeFilter} onChange={(e) => setTypeFilter(e.target.value)}>
            <option value="all">ทุกประเภท</option>
            <option value="receive">รับเข้า</option>
            <option value="issue">เบิกจ่าย</option>
            <option value="transfer">โอนย้าย</option>
          </select>
          <select value={catFilter} onChange={(e) => setCatFilter(e.target.value)}>
            <option value="all">ทุกหมวด</option>
            {state.categories.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
          </select>
          <select value={projFilter} onChange={(e) => setProjFilter(e.target.value)}>
            <option value="all">ทุกหน่วยงาน</option>
            {state.projects.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
          <button className="btn-ghost" onClick={() => exportCSV("movement", state, null, null, null, rows)}>⬇ CSV</button>
        </div>
      </div>

      <div className="stat-grid">
        <StatCard label="จำนวนธุรกรรม" value={fmtNum(rows.length)} accent="#111" icon="📑" />
        <StatCard label="รับเข้า" value={fmtNum(sums.receive)} accent="#1F8A5B" icon="📥" />
        <StatCard label="เบิกจ่าย" value={fmtNum(sums.issue)} accent="#D9534F" icon="📤" />
        <StatCard label="โอนย้าย" value={fmtNum(sums.transfer)} accent="#7B61FF" icon="🔄" />
      </div>

      <div className="card no-pad">
        <table className="data-table">
          <thead>
            <tr>
              <th>เลขที่</th>
              <th>วันที่</th>
              <th>ประเภท</th>
              <th>วัสดุ</th>
              <th>หมวด</th>
              <th>หน่วยงาน</th>
              <th className="num-col">จำนวน</th>
              <th>หมายเหตุ</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 && <tr><td colSpan="8"><Empty /></td></tr>}
            {rows.map((t) => {
              const m = matMap[t.materialId];
              const meta = t.type === "receive" ? { label: "รับเข้า", color: "#1F8A5B", sign: "+" }
                : t.type === "issue" ? { label: "เบิกจ่าย", color: "#D9534F", sign: "−" }
                : { label: "โอนย้าย", color: "#7B61FF", sign: "↔" };
              return (
                <tr key={t.id}>
                  <td className="mono">{t.id}</td>
                  <td>{fmtDate(t.date)}</td>
                  <td><span className="status-pill" style={{ background: meta.color + "1a", color: meta.color }}>{meta.label}</span></td>
                  <td><b>{m?.name}</b></td>
                  <td><CatBadge cat={m ? catMap[m.category] : null} /></td>
                  <td>{t.type === "transfer" ? <span>{projMap[t.fromProjectId]?.code} → {projMap[t.toProjectId]?.code}</span> : projMap[t.projectId]?.name}</td>
                  <td className="num-col" style={{ color: meta.color, fontWeight: 700 }}>{meta.sign}{fmtNum(t.qty)} <span className="muted">{m?.unit}</span></td>
                  <td className="muted">{t.note || t.supplier || t.requester || "—"}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
}

// -------- 3) Transfer report --------
function TransferReport({ state }) {
  const matMap = Object.fromEntries(state.materials.map((m) => [m.id, m]));
  const projMap = Object.fromEntries(state.projects.map((p) => [p.id, p]));
  const catMap = Object.fromEntries(state.categories.map((c) => [c.id, c]));

  const transfers = state.transactions.filter((t) => t.type === "transfer").sort((a, b) => new Date(b.date) - new Date(a.date));

  // Matrix from→to count
  const matrix = {};
  state.projects.forEach((p) => { matrix[p.id] = {}; state.projects.forEach((q) => matrix[p.id][q.id] = 0); });
  transfers.forEach((t) => { matrix[t.fromProjectId][t.toProjectId] += t.qty; });

  return (
    <>
      <div className="card">
        <div className="card-head">
          <h3>เมทริกซ์การโอนย้าย (รวมจำนวน)</h3>
          <span className="muted">แถว = ต้นทาง · คอลัมน์ = ปลายทาง</span>
        </div>
        <div className="table-wrap">
          <table className="data-table matrix">
            <thead>
              <tr>
                <th>จาก ↓ / ไป →</th>
                {state.projects.map((p) => <th key={p.id} className="num-col">{p.code}</th>)}
                <th className="num-col">รวมส่งออก</th>
              </tr>
            </thead>
            <tbody>
              {state.projects.map((from) => {
                const rowSum = state.projects.reduce((a, to) => a + matrix[from.id][to.id], 0);
                return (
                  <tr key={from.id}>
                    <td><b>{from.code}</b> <span className="muted small">{from.name}</span></td>
                    {state.projects.map((to) => {
                      const v = matrix[from.id][to.id];
                      const same = from.id === to.id;
                      return (
                        <td key={to.id} className="num-col" style={{ background: same ? "#f4f4f4" : v > 0 ? "#f0eaff" : undefined, color: same ? "#bbb" : v > 0 ? "#5a45c0" : "#111", fontWeight: v > 0 ? 700 : 400 }}>
                          {same ? "—" : fmtNum(v)}
                        </td>
                      );
                    })}
                    <td className="num-col"><b>{fmtNum(rowSum)}</b></td>
                  </tr>
                );
              })}
              <tr style={{ background: "#fafafa" }}>
                <td><b>รวมรับเข้า</b></td>
                {state.projects.map((to) => {
                  const colSum = state.projects.reduce((a, from) => a + matrix[from.id][to.id], 0);
                  return <td key={to.id} className="num-col"><b>{fmtNum(colSum)}</b></td>;
                })}
                <td className="num-col"><b>{fmtNum(transfers.reduce((a, t) => a + t.qty, 0))}</b></td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <div className="card no-pad">
        <div className="card-head" style={{ padding: 16 }}>
          <h3>รายการโอนย้ายทั้งหมด ({transfers.length})</h3>
          <button className="btn-ghost" onClick={() => exportCSV("transfer", state, null, null, null, transfers)}>⬇ CSV</button>
        </div>
        <table className="data-table">
          <thead>
            <tr>
              <th>เลขที่</th>
              <th>วันที่</th>
              <th>วัสดุ</th>
              <th>หมวด</th>
              <th>ต้นทาง</th>
              <th>ปลายทาง</th>
              <th className="num-col">จำนวน</th>
              <th>ผู้บันทึก</th>
            </tr>
          </thead>
          <tbody>
            {transfers.length === 0 && <tr><td colSpan="8"><Empty /></td></tr>}
            {transfers.map((t) => {
              const m = matMap[t.materialId];
              return (
                <tr key={t.id}>
                  <td className="mono">{t.id}</td>
                  <td>{fmtDate(t.date)}</td>
                  <td><b>{m?.name}</b></td>
                  <td><CatBadge cat={m ? catMap[m.category] : null} /></td>
                  <td>{projMap[t.fromProjectId]?.name} <div className="muted small">{projMap[t.fromProjectId]?.code}</div></td>
                  <td>{projMap[t.toProjectId]?.name} <div className="muted small">{projMap[t.toProjectId]?.code}</div></td>
                  <td className="num-col"><b style={{ color: "#7B61FF" }}>{fmtNum(t.qty)}</b> <span className="muted">{m?.unit}</span></td>
                  <td className="muted">{t.by}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
}

// -------- CSV export --------
function exportCSV(kind, state, stock, catFilter, projFilter, rows) {
  let csv = "";
  if (kind === "balance") {
    const headers = ["รหัส", "วัสดุ", "หมวด", "หน่วย", ...state.projects.map((p) => p.code), "รวม", "ขั้นต่ำ", "สถานะ"];
    csv = "\uFEFF" + headers.join(",") + "\n";
    state.materials.filter((m) => catFilter === "all" || m.category === catFilter).forEach((m) => {
      const total = materialTotal(stock, m.id);
      const status = total <= 0 ? "หมด" : total < m.min ? "ต่ำ" : "ปกติ";
      const row = [m.id, m.name, state.categories.find((c) => c.id === m.category)?.name, m.unit,
        ...state.projects.map((p) => stock[m.id]?.[p.id] || 0), total, m.min, status];
      csv += row.map((x) => `"${x}"`).join(",") + "\n";
    });
  } else {
    const headers = ["เลขที่", "วันที่", "ประเภท", "วัสดุ", "หมวด", "ต้นทาง/หน่วยงาน", "ปลายทาง", "จำนวน", "หน่วย", "หมายเหตุ", "ผู้บันทึก"];
    csv = "\uFEFF" + headers.join(",") + "\n";
    const mMap = Object.fromEntries(state.materials.map((m) => [m.id, m]));
    const pMap = Object.fromEntries(state.projects.map((p) => [p.id, p]));
    const cMap = Object.fromEntries(state.categories.map((c) => [c.id, c]));
    rows.forEach((t) => {
      const m = mMap[t.materialId];
      const row = [t.id, fmtDate(t.date), t.type, m?.name, cMap[m?.category]?.name,
        t.type === "transfer" ? pMap[t.fromProjectId]?.name : pMap[t.projectId]?.name,
        t.type === "transfer" ? pMap[t.toProjectId]?.name : "",
        t.qty, m?.unit, t.note || t.supplier || t.requester || "", t.by];
      csv += row.map((x) => `"${(x || "").toString().replace(/"/g, '""')}"`).join(",") + "\n";
    });
  }
  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 = `report_${kind}_${new Date().toISOString().slice(0, 10)}.csv`; a.click();
  URL.revokeObjectURL(url);
}

window.ReportsPage = ReportsPage;
