"use client";

import { useEffect, useState } from "react";
import { format } from "date-fns";
import { getMetrics, exportMetricsCsv, type InstanceMetrics } from "@/lib/admin-rpc";

export default function MetricsPage() {
  const [metrics, setMetrics] = useState<InstanceMetrics[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [exporting, setExporting] = useState(false);
  const [instanceFilter, setInstanceFilter] = useState("");

  useEffect(() => { loadMetrics(); }, []);

  async function loadMetrics() {
    setLoading(true);
    setError("");
    try {
      const data = await getMetrics(instanceFilter);
      setMetrics(data);
    } catch (e) {
      setError(e instanceof Error ? e.message : "加载指标失败");
    } finally {
      setLoading(false);
    }
  }

  async function handleExportCsv() {
    setExporting(true);
    try {
      const csv = await exportMetricsCsv(instanceFilter);
      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 = `metrics-${format(new Date(), "yyyy-MM-dd_HHmm")}.csv`;
      a.click();
      URL.revokeObjectURL(url);
    } catch (e) {
      alert("导出失败: " + (e instanceof Error ? e.message : String(e)));
    } finally {
      setExporting(false);
    }
  }

  // Group by instance
  const byInstance = metrics.reduce<Record<string, InstanceMetrics[]>>((acc, m) => {
    if (!acc[m.instance_id]) acc[m.instance_id] = [];
    acc[m.instance_id].push(m);
    return acc;
  }, {});

  const allInstances = Object.keys(byInstance).sort();
  const latestOf = (arr: InstanceMetrics[]) =>
    arr.sort((a, b) => b.timestamp_secs - a.timestamp_secs)[0];

  // Flatten all latest snapshots for a summary table
  const latestSnapshots = allInstances.map((id) => ({
    id,
    latest: latestOf(byInstance[id]),
  }));

  function metricVal(m: InstanceMetrics | undefined, prefix: string, key: string): string {
    if (!m) return "—";
    const v = prefix === "http" ? m.http[key] : m.room[key];
    return v ?? "—";
  }

  return (
    <div className="admin-content">
      <div className="page-header" style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <h1 className="page-title">应用指标监控</h1>
          <p className="page-subtitle">
            共 {allInstances.length} 个实例
            {metrics.length > 0 && (
              <span style={{ marginLeft: "8px", fontSize: "12px", color: "#737373" }}>
                最新数据: {metrics.length > 0
                  ? format(new Date(latestSnapshots[0]?.latest.timestamp_secs * 1000), "yyyy-MM-dd HH:mm:ss")
                  : "—"}
              </span>
            )}
          </p>
        </div>
        <div style={{ display: "flex", gap: "8px", alignItems: "center" }}>
          <input
            type="text"
            className="form-input"
            style={{ width: "200px" }}
            placeholder="过滤实例名称..."
            value={instanceFilter}
            onChange={(e) => { setInstanceFilter(e.target.value); }}
          />
          <button className="btn btn-secondary" onClick={loadMetrics} disabled={loading}>
            {loading ? "加载中..." : "刷新"}
          </button>
          <button className="btn btn-primary" onClick={handleExportCsv} disabled={exporting}>
            {exporting ? "导出中..." : "导出 CSV"}
          </button>
        </div>
      </div>

      {error && (
        <div className="alert alert-error" style={{ marginBottom: "16px" }}>
          {error} — 确认 adminrpc 服务正在运行（默认: http://adminrpc.admin.svc.cluster.local:9091）
        </div>
      )}

      {loading ? (
        <div className="loading">加载中...</div>
      ) : allInstances.length === 0 ? (
        <div className="card">
          <div className="empty-state">
            <div className="empty-state-icon">◉</div>
            <p>暂无指标数据</p>
            <p style={{ fontSize: "13px", color: "#737373" }}>
              确认应用已将指标刷新到 Redis（每 5 秒一次）
            </p>
          </div>
        </div>
      ) : (
        <>
          {/* Summary table */}
          <div className="card" style={{ marginBottom: "16px" }}>
            <h3 style={{ margin: "0 0 12px 0", fontSize: "14px", fontWeight: 600 }}>实例概览</h3>
            <div className="table-container">
              <table className="data-table">
                <thead>
                  <tr>
                    <th>实例 ID</th>
                    <th>最后更新</th>
                    <th>活跃 WS 连接</th>
                    <th>发送消息数</th>
                    <th>HTTP 请求数</th>
                    <th>HTTP 错误数</th>
                  </tr>
                </thead>
                <tbody>
                  {latestSnapshots.map(({ id, latest }) => (
                    <tr key={id}>
                      <td><code style={{ fontSize: "12px" }}>{id}</code></td>
                      <td>{format(new Date(latest.timestamp_secs * 1000), "HH:mm:ss")}</td>
                      <td>{metricVal(latest, "room", "ws_connections_active")}</td>
                      <td>{metricVal(latest, "room", "messages_sent_total")}</td>
                      <td>{metricVal(latest, "http", "request_count")}</td>
                      <td>{metricVal(latest, "http", "error_count")}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {/* Per-instance detail */}
          {allInstances.map((instanceId) => (
            <div key={instanceId} className="card" style={{ marginBottom: "16px" }}>
              <h3 style={{ margin: "0 0 12px 0", fontSize: "14px", fontWeight: 600 }}>
                实例: <code>{instanceId}</code>
              </h3>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px" }}>
                {/* Room metrics */}
                <div>
                  <h4 style={{ fontSize: "13px", color: "#737373", margin: "0 0 8px 0" }}>Room 指标</h4>
                  <div style={{ display: "flex", flexDirection: "column", gap: "4px", fontSize: "13px" }}>
                    {Object.entries(latestOf(byInstance[instanceId])?.room ?? {}).map(([k, v]) => (
                      <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "2px 0", borderBottom: "1px solid #f4f4f5" }}>
                        <span style={{ color: "#525252" }}>{k}</span>
                        <code style={{ fontSize: "12px", color: "#171717" }}>{v}</code>
                      </div>
                    ))}
                    {Object.keys(latestOf(byInstance[instanceId])?.room ?? {}).length === 0 && (
                      <div style={{ color: "#a3a3a3", fontSize: "12px" }}>无数据</div>
                    )}
                  </div>
                </div>
                {/* HTTP metrics */}
                <div>
                  <h4 style={{ fontSize: "13px", color: "#737373", margin: "0 0 8px 0" }}>HTTP 指标</h4>
                  <div style={{ display: "flex", flexDirection: "column", gap: "4px", fontSize: "13px" }}>
                    {Object.entries(latestOf(byInstance[instanceId])?.http ?? {}).map(([k, v]) => (
                      <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "2px 0", borderBottom: "1px solid #f4f4f5" }}>
                        <span style={{ color: "#525252" }}>{k}</span>
                        <code style={{ fontSize: "12px", color: "#171717" }}>{v}</code>
                      </div>
                    ))}
                    {Object.keys(latestOf(byInstance[instanceId])?.http ?? {}).length === 0 && (
                      <div style={{ color: "#a3a3a3", fontSize: "12px" }}>无数据</div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </>
      )}
    </div>
  );
}
