import { useEffect, useState } from 'react';
import { Card, Spin, Table, Tag, Typography } from 'antd';
import {
  getDashboardSummary,
  type DashboardSummary,
} from '../api/dashboard';
import StatCards from '../components/StatCard';

const { Title } = Typography;

const columns = [
  { title: '代码', dataIndex: 'code', key: 'code', width: 80 },
  { title: '名称', dataIndex: 'name', key: 'name', width: 100 },
  {
    title: '最新价',
    dataIndex: 'close',
    key: 'close',
    width: 80,
    render: (v: number) => v?.toFixed(2),
  },
  {
    title: '涨跌幅',
    dataIndex: 'pct_change',
    key: 'pct_change',
    width: 90,
    render: (v: number) => {
      const is20 = Math.abs(v) >= 19.5;
      return (
        <Tag color={v >= 0 ? 'red' : 'green'} style={is20 ? { fontWeight: 'bold' } : undefined}>
          {v >= 0 ? '+' : ''}{v?.toFixed(2)}%
        </Tag>
      );
    },
  },
];

export default function Dashboard() {
  const [summary, setSummary] = useState<DashboardSummary | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    getDashboardSummary()
      .then(setSummary)
      .finally(() => setLoading(false));
  }, []);

  if (loading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', padding: 100 }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!summary) return <div>加载失败</div>;

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto' }}>
      <Title level={2} style={{ textAlign: 'center', marginBottom: 32 }}>
        A股市场概览
      </Title>

      <StatCards data={summary} />

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 24 }}>
        <Card title={`涨停 (${summary.limit_up_list.length}只)`} size="small">
          <Table
            columns={columns}
            dataSource={summary.limit_up_list}
            rowKey="code"
            pagination={{ pageSize: 50, size: 'small', showSizeChanger: false }}
            size="small"
            scroll={{ y: 400 }}
          />
        </Card>
        <Card title={`跌停 (${summary.limit_down_list.length}只)`} size="small">
          <Table
            columns={columns}
            dataSource={summary.limit_down_list}
            rowKey="code"
            pagination={{ pageSize: 50, size: 'small', showSizeChanger: false }}
            size="small"
            scroll={{ y: 400 }}
          />
        </Card>
      </div>

      <Card title={`百日新高 (${summary.high_100_list.length}只)`} size="small" style={{ marginTop: 16 }}>
        <Table
          columns={columns}
          dataSource={summary.high_100_list}
          rowKey="code"
          pagination={{ pageSize: 50, size: 'small', showSizeChanger: false }}
          size="small"
          scroll={{ y: 400 }}
        />
      </Card>
    </div>
  );
}
