/* Tachiara client — Stats screen.
 * Loads all my rooms + their bills in parallel, then computes everything client-side.
 */

function StatsScreen({ me, navigate }) {
  const { data, loading, error, reload } = useApi(async () => {
    const { rooms } = await window.api.rooms.list();
    // For each room, fetch bills + settlements in parallel
    const detailed = await Promise.all(rooms.map(async (room) => {
      const [{ bills }, { settlements }] = await Promise.all([
        window.api.bills.list(room.id),
        window.api.settlements.list(room.id),
      ]);
      return { room, bills, settlements };
    }));
    return { rooms: detailed };
  }, []);

  if (loading) return <LoadingState />;
  if (error) return <ErrorState error={error} onRetry={reload} />;

  const allRooms = data.rooms;
  const allBills = allRooms.flatMap(r => r.bills);

  const totalSpent = allBills.reduce((s, b) => s + b.totalAmount, 0);

  let myShareTotal = 0;
  allBills.forEach(b => {
    const split = window.QC.splitToAmounts(b);
    myShareTotal += split[me.id] || 0;
  });
  const myPaid = allBills.filter(b => b.paidById === me.id).reduce((s, b) => s + b.totalAmount, 0);

  let netAll = 0;
  allRooms.forEach(({ room, bills, settlements }) => {
    const bal = window.QC.computeBalances(room.memberIds, bills, settlements);
    netAll += bal[me.id] || 0;
  });

  const byRoom = allRooms.map(({ room, bills }) => ({
    label: room.name,
    value: bills.reduce((s, b) => s + b.totalAmount, 0),
    color: window.QC.avatarColor(room.name),
  })).sort((a, b) => b.value - a.value);

  const months = [];
  const now = new Date();
  for (let i = 5; i >= 0; i--) {
    const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
    months.push({
      key: d.getFullYear() + "-" + d.getMonth(),
      label: (d.getMonth() + 1) + "/" + String(d.getFullYear()).slice(2),
      value: 0,
    });
  }
  allBills.forEach(b => {
    const d = new Date(b.createdAt);
    const key = d.getFullYear() + "-" + d.getMonth();
    const m = months.find(x => x.key === key);
    if (m) m.value += b.totalAmount;
  });
  const maxMonth = Math.max(...months.map(m => m.value), 1);

  const modeCount = {};
  allBills.forEach(b => modeCount[b.splitMode] = (modeCount[b.splitMode] || 0) + 1);
  const modeSegments = [
    { label: "Chia đều",  value: modeCount.equal   || 0, color: "#0F172A" },
    { label: "Chọn người", value: modeCount.select  || 0, color: "#475569" },
    { label: "Số tiền",   value: modeCount.amount  || 0, color: "#94A3B8" },
    { label: "Theo %",    value: modeCount.percent || 0, color: "#0F766E" },
    { label: "Theo phần", value: modeCount.shares  || 0, color: "#B45309" },
  ].filter(s => s.value > 0);

  return (
    <div>
      <div className="page-header">
        <div>
          <h1 className="page-title">Thống kê</h1>
          <div className="page-subtitle">Tổng quan chi tiêu của bạn qua các phòng.</div>
        </div>
      </div>

      <div className="grid-stats" style={{ marginBottom: 24 }}>
        <div className="card card-tight"><div className="stat">
          <div className="stat-label">Tổng chi (tất cả phòng)</div>
          <div className="stat-value">{window.QC.formatVNDShort(totalSpent)}</div>
          <div className="stat-meta">{allBills.length} khoản</div>
        </div></div>
        <div className="card card-tight"><div className="stat">
          <div className="stat-label">Bạn đã trả thay</div>
          <div className="stat-value">{window.QC.formatVNDShort(myPaid)}</div>
          <div className="stat-meta">{allBills.filter(b => b.paidById === me.id).length} lần</div>
        </div></div>
        <div className="card card-tight"><div className="stat">
          <div className="stat-label">Phần của bạn</div>
          <div className="stat-value">{window.QC.formatVNDShort(myShareTotal)}</div>
          <div className="stat-meta">Tính trên các bill có bạn</div>
        </div></div>
        <div className="card card-tight"><div className="stat">
          <div className="stat-label">Net hiện tại</div>
          <div className={"stat-value " + (netAll > 0 ? "money-positive" : netAll < 0 ? "money-negative" : "money-zero")}>
            {Math.abs(netAll) < 100 ? "0 ₫" : window.QC.formatVNDShort(Math.abs(netAll))}
          </div>
          <div className="stat-meta">{netAll > 0 ? "Được trả" : netAll < 0 ? "Phải trả" : "Đã cân"}</div>
        </div></div>
      </div>

      <div className="grid-2">
        <div className="card">
          <div className="section-title">Chi tiêu theo phòng</div>
          {byRoom.length === 0 ? <Empty>Chưa có dữ liệu.</Empty> : (
            <div className="row-h" style={{ alignItems: "center", gap: 24 }}>
              <Donut segments={byRoom} size={180} thickness={24} />
              <div style={{ flex: 1 }}>
                {byRoom.map((r, i) => (
                  <div key={i} className="row-h" style={{ padding: "6px 0", gap: 10 }}>
                    <div style={{ width: 10, height: 10, borderRadius: 2, background: r.color, flexShrink: 0 }} />
                    <div style={{ flex: 1, fontSize: 13, fontWeight: 500 }}>{r.label}</div>
                    <div className="mono text-xs">{window.QC.formatVNDShort(r.value)}</div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        <div className="card">
          <div className="section-title">6 tháng gần nhất</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", alignItems: "end", gap: 12, height: 180, padding: "12px 4px" }}>
            {months.map(m => (
              <div key={m.key} style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "flex-end", height: "100%", gap: 6 }}>
                <div className="text-xs mono fw-600" style={{ color: "var(--wf-fg-2)" }}>
                  {m.value > 0 ? window.QC.formatVNDShort(m.value) : ""}
                </div>
                <div style={{
                  width: "100%",
                  height: Math.max((m.value / maxMonth) * 130, m.value > 0 ? 4 : 0) + "px",
                  background: "var(--wf-slate-900)",
                  borderRadius: "6px 6px 0 0",
                  transition: "height var(--dur-slow) var(--ease-out)",
                }} />
                <div className="text-xs text-muted">{m.label}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div className="section-title">Loại chia phổ biến</div>
          {modeSegments.length === 0 ? <Empty>Chưa có bill nào.</Empty> : (
            <div className="row-h" style={{ alignItems: "center", gap: 24 }}>
              <Donut segments={modeSegments} size={160} thickness={22} />
              <div style={{ flex: 1 }}>
                {modeSegments.map((m, i) => (
                  <div key={i} className="row-h" style={{ padding: "6px 0", gap: 10 }}>
                    <div style={{ width: 10, height: 10, borderRadius: 2, background: m.color, flexShrink: 0 }} />
                    <div style={{ flex: 1, fontSize: 13, fontWeight: 500 }}>{m.label}</div>
                    <div className="mono text-xs text-muted">{m.value} lần</div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        <div className="card">
          <div className="section-title">Top khoản chi</div>
          {allBills.length === 0 ? <Empty>Chưa có khoản chi nào.</Empty> : allBills.slice().sort((a, b) => b.totalAmount - a.totalAmount).slice(0, 5).map(bill => {
            const room = allRooms.find(r => r.room.id === bill.roomId)?.room;
            return (
              <div key={bill.id} className="row">
                <div className="activity-icon"><span className="icon"><I.receipt /></span></div>
                <div className="row-main">
                  <div className="row-title">{bill.title}</div>
                  <div className="row-sub">{room?.name} · {window.QC.timeAgo(bill.createdAt)}</div>
                </div>
                <div className="money">{window.QC.formatVND(bill.totalAmount)}</div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.StatsScreen = StatsScreen;
