import { useEffect, useState } from 'react';
import { Card, Spin, Table, Tag, Typography } from 'antd';
import { getConsecutiveLimits, type ConsecutiveLimit } from '../api/dashboard';

const { Title } = Typography;

const columns = [
  {
    title: '连板',
    dataIndex: 'streak',
    key: 'streak',
    width: 70,
    render: (v: number) => (
      <Tag color={v >= 5 ? '#722ed1' : v >= 3 ? '#cf1322' : '#fa541c'} style={{ fontWeight: 'bold', fontSize: 14 }}>
        {v}连板
      </Tag>
    ),
  },
  { 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) => (
      <Tag color="red">{v >= 0 ? '+' : ''}{v?.toFixed(2)}%</Tag>
    ),
  },
];

export default function ConsecutivePage() {
  const [data, setData] = useState<ConsecutiveLimit[]>([]);
  const [loading, setLoading] = useState(true);

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

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

  // Group by streak
  const grouped = data.reduce<Record<number, ConsecutiveLimit[]>>((acc, item) => {
    if (!acc[item.streak]) acc[item.streak] = [];
    acc[item.streak].push(item);
    return acc;
  }, {});

  const maxStreak = data.length > 0 ? data[0].streak : 0;

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto' }}>
      <Title level={2} style={{ textAlign: 'center', marginBottom: 32 }}>
        连板高度
      </Title>

      <Card style={{ marginBottom: 16, textAlign: 'center' }}>
        <Title level={4} style={{ margin: 0 }}>
          今日涨停 <span style={{ color: '#cf1322' }}>{data.length}</span> 只，
          最高 <span style={{ color: '#722ed1', fontSize: 28 }}>{maxStreak}</span> 连板
        </Title>
      </Card>

      {Object.keys(grouped)
        .sort((a, b) => Number(b) - Number(a))
        .map((streak) => (
          <Card
            key={streak}
            title={`${streak}连板 (${grouped[Number(streak)].length}只)`}
            size="small"
            style={{ marginBottom: 12 }}
          >
            <Table
              columns={columns}
              dataSource={grouped[Number(streak)]}
              rowKey="code"
              pagination={false}
              size="small"
            />
          </Card>
        ))}
    </div>
  );
}
