import { useEffect, useState } from 'react';
import { fetchAnalytics } from '../api/client';

export function AnalyticsPage() {
  const [data, setData] = useState<Awaited<ReturnType<typeof fetchAnalytics>> | null>(null);
  const [error, setError] = useState<string | null>(null);

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

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

  return (
    <div className="grid">
      <div className="card" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(160px,1fr))', gap: 12 }}>
        <div>
          <p>今日新帖</p>
          <strong style={{ fontSize: 28 }}>{data.today.new_posts}</strong>
          <p style={{ color: '#68716c', fontSize: 12 }}>昨日 {data.yesterday.new_posts}</p>
        </div>
        <div>
          <p>广场注册</p>
          <strong style={{ fontSize: 28 }}>{data.today.plaza_signups}</strong>
        </div>
        <div>
          <p>待审核</p>
          <strong style={{ fontSize: 28 }}>{data.today.pending_review}</strong>
        </div>
      </div>
      <div className="card">
        <h3>分类分布</h3>
        <ul>
          {data.categories.map((item) => (
            <li key={item.name}>
              {item.name}: {item.count}
            </li>
          ))}
        </ul>
      </div>
      <div className="card">
        <h3>TOP 创作者</h3>
        <ul>
          {data.top_creators.map((creator) => (
            <li key={creator.slug}>
              {creator.display_name} · {creator.post_count} 篇 · {creator.total_likes} 赞
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}
