'use client';

import React, { useEffect, useState } from 'react';
import { Card, Col, Row, Statistic, Spin } from 'antd';
import {
  ApiOutlined,
  TeamOutlined,
  WarningOutlined,
} from '@ant-design/icons';
import { Line } from '@ant-design/charts';
import AdminLayout from '@/components/AdminLayout';
import { getDashboardStats, getDashboardTrend } from '@/services/api';

interface Stats { today_total_calls: number; active_clients: number; error_calls: number; }
interface TrendPoint { hour: string; count: number; }

export default function DashboardPage() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [trend, setTrend] = useState<TrendPoint[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [statsRes, trendRes] = await Promise.all([
          getDashboardStats(),
          getDashboardTrend(),
        ]);
        setStats(statsRes.data);
        setTrend(trendRes.data);
      } catch (err) {
        console.error(err);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  if (loading) return <AdminLayout><Spin size="large" style={{ display: 'block', margin: '100px auto' }} /></AdminLayout>;

  return (
    <AdminLayout>
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={8}>
          <Card>
            <Statistic
              title="今日 API 调用总数"
              value={stats?.today_total_calls ?? 0}
              prefix={<ApiOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="活跃客户数"
              value={stats?.active_clients ?? 0}
              prefix={<TeamOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="异常调用数"
              value={stats?.error_calls ?? 0}
              prefix={<WarningOutlined />}
              valueStyle={{ color: stats?.error_calls ? '#ff4d4f' : '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>

      <Card title="近 24 小时 API 调用趋势" style={{ marginBottom: 24 }}>
        {trend.length > 0 ? (
          <Line
            data={trend.map(p => ({ time: p.hour.slice(5, 16), count: Number(p.count), fullHour: p.hour }))}
            xField="time"
            yField="count"
            smooth
            height={280}
            color="#1890ff"
            axis={{
              x: { title: { text: '时间' }, label: { autoRotate: false }, grid: { line: { style: { stroke: '#333', lineWidth: 2 } } } },
              y: { title: { text: '调用次数' }, min: 0, grid: { line: { style: { stroke: '#333', lineWidth: 2 } } } },
            }}
            tooltip={{
              title: (datum: { fullHour: string }) => datum.fullHour,
              items: [
                (datum: { count: number }) => ({
                  name: '调用次数',
                  value: datum.count,
                }),
              ],
            }}
          />
        ) : (
          <div style={{ textAlign: 'center', color: '#999', padding: 40 }}>暂无调用数据</div>
        )}
      </Card>
    </AdminLayout>
  );
}
