import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { fetchAdminSummary, type AdminSummary } from '../../api/admin';

function yuan(cents: number) {
  return `¥${(cents / 100).toFixed(2)}`;
}

export function SummaryPage() {
  const [summary, setSummary] = useState<AdminSummary | null>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    void fetchAdminSummary()
      .then((r) => setSummary(r.summary))
      .catch((err) => setError(err instanceof Error ? err.message : '加载失败'));
  }, []);

  if (error) return <p className="alert">{error}</p>;
  if (!summary) return <p>加载中…</p>;

  return (
    <div className="grid">
      <div
        className="card"
        style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))', gap: 12 }}
      >
        <div>
          <p style={{ color: '#68716c', marginBottom: 4 }}>总用户</p>
          <strong style={{ fontSize: 28 }}>{summary.totalUsers}</strong>
        </div>
        <div>
          <p style={{ color: '#68716c', marginBottom: 4 }}>活跃用户</p>
          <strong style={{ fontSize: 28 }}>{summary.activeUsers}</strong>
        </div>
        <div>
          <p style={{ color: '#68716c', marginBottom: 4 }}>平台余额总计</p>
          <strong style={{ fontSize: 28 }}>{yuan(summary.totalBalanceCents)}</strong>
        </div>
      </div>

      {summary.llm ? (
        <div className="card">
          <h3 style={{ marginTop: 0 }}>LLM 状态</h3>
          <p>已配置密钥：{summary.llm.keyCount} 条</p>
          <p>当前选中：{summary.llm.selectedKeyName ?? '（无）'}</p>
          <p>全局模型：{summary.llm.globalModel ?? '（未设置）'}</p>
        </div>
      ) : (
        <div className="card">
          <p style={{ color: '#68716c' }}>LLM 服务未启用</p>
        </div>
      )}

      <div
        className="card"
        style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}
      >
        <div>
          <h3 style={{ marginTop: 0, marginBottom: 8 }}>常用入口</h3>
          <p style={{ color: '#68716c', marginTop: 0 }}>
            这里可以直接进入用户充值、服务号通知和网页端通知管理。
          </p>
        </div>
        <Link className="btn" to="/admin/wechat" style={{ textAlign: 'center', textDecoration: 'none' }}>
          进入通知推送
        </Link>
        <Link
          className="btn secondary"
          to="/admin/users"
          style={{ textAlign: 'center', textDecoration: 'none' }}
        >
          进入用户管理
        </Link>
      </div>
    </div>
  );
}
