"use client";

import { useEffect, useState } from "react";
import { format } from "date-fns";

interface MetricData {
  total: number;
  last_27h: number;
  last_7d: number;
  last_30d: number;
}

interface MetricsResponse {
  metrics: Record<string, MetricData>;
  timestamp: string;
}

const ENTITY_LABELS: Record<string, { label: string; icon: string }> = {
  users: { label: "用户", icon: "👤" },
  workspaces: { label: "Workspace", icon: "◎" },
  projects: { label: "项目", icon: "◻" },
  repos: { label: "仓库", icon: "◈" },
  rooms: { label: "房间", icon: "◫" },
  skills: { label: "Skills", icon: "⚡" },
};

export default function MetricsPage() {
  const [data, setData] = useState<MetricsResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [lastRefresh, setLastRefresh] = useState<string | null>(null);

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

  function loadMetrics() {
    setLoading(true);
    fetch("/api/metrics")
      .then((r) => r.json())
      .then((d) => {
        setData(d);
        setLastRefresh(new Date().toISOString());
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }

  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">
            各实体数量统计
            {lastRefresh && (
              <span style={{ marginLeft: "8px", fontSize: "12px", color: "#737373" }}>
                更新于 {format(new Date(lastRefresh), "HH:mm:ss")}
              </span>
            )}
          </p>
        </div>
        <button className="btn btn-secondary" onClick={loadMetrics}>刷新</button>
      </div>

      {loading ? (
        <div className="loading">加载中...</div>
      ) : data ? (
        <>
          {/* Summary cards */}
          <div className="stats-grid" style={{ gridTemplateColumns: "repeat(auto-fill, minmax(200px, 1fr))" }}>
            {Object.entries(data.metrics).map(([key, val]) => {
              const meta = ENTITY_LABELS[key];
              if (!meta) return null;
              return (
                <div key={key} className="stat-card">
                  <div className="stat-label" style={{ fontSize: "14px", marginBottom: "4px" }}>
                    {meta.icon} {meta.label}
                  </div>
                  <div className="stat-value" style={{ fontSize: "28px" }}>
                    {val.total.toLocaleString()}
                  </div>
                  <div className="stat-label">总计</div>
                </div>
              );
            })}
          </div>

          {/* Detail table */}
          <div className="card" style={{ marginTop: "16px" }}>
            <div className="table-container">
              <table className="data-table">
                <thead>
                  <tr>
                    <th>实体</th>
                    <th>总计</th>
                    <th>过去 27 小时新增</th>
                    <th>过去 7 天新增</th>
                    <th>过去 30 天新增</th>
                  </tr>
                </thead>
                <tbody>
                  {Object.entries(data.metrics).map(([key, val]) => {
                    const meta = ENTITY_LABELS[key];
                    if (!meta) return null;
                    return (
                      <tr key={key}>
                        <td>
                          <span style={{ fontWeight: 500 }}>{meta.icon} {meta.label}</span>
                        </td>
                        <td style={{ fontWeight: 600 }}>{val.total.toLocaleString()}</td>
                        <td>
                          <span className="badge badge-neutral">
                            +{val.last_27h.toLocaleString()}
                          </span>
                          {val.last_27h > 0 && (
                            <span style={{ marginLeft: "6px", fontSize: "12px", color: "#16a34a" }}>
                              ({((val.last_27h / Math.max(val.total, 1)) * 100).toFixed(1)}%)
                            </span>
                          )}
                        </td>
                        <td>
                          <span className="badge badge-neutral">
                            +{val.last_7d.toLocaleString()}
                          </span>
                          {val.last_7d > 0 && (
                            <span style={{ marginLeft: "6px", fontSize: "12px", color: "#16a34a" }}>
                              ({((val.last_7d / Math.max(val.total, 1)) * 100).toFixed(1)}%)
                            </span>
                          )}
                        </td>
                        <td>
                          <span className="badge badge-neutral">
                            +{val.last_30d.toLocaleString()}
                          </span>
                          {val.last_30d > 0 && (
                            <span style={{ marginLeft: "6px", fontSize: "12px", color: "#16a34a" }}>
                              ({((val.last_30d / Math.max(val.total, 1)) * 100).toFixed(1)}%)
                            </span>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>

          {/* Raw JSON for API consumers */}
          <div className="card" style={{ marginTop: "16px" }}>
            <h3 style={{ margin: "0 0 8px 0", fontSize: "14px", fontWeight: 600 }}>API 端点</h3>
            <p style={{ margin: "0 0 8px 0", fontSize: "13px", color: "#737373" }}>
              通过 <code>GET /api/metrics</code> 获取 JSON 格式指标数据，可用于 Prometheus 或其他监控系统采集。
            </p>
            <pre style={{ background: "#1e1e1e", color: "#d4d4d4", padding: "16px", borderRadius: "8px", fontSize: "12px", overflow: "auto" }}>
              {JSON.stringify(data, null, 2)}
            </pre>
          </div>
        </>
      ) : (
        <div className="alert alert-error">无法加载指标数据</div>
      )}
    </div>
  );
}
