import { Row, Col, Card, Statistic, List, Spin, Typography, Flex, Button } from 'antd';
import {
  TrophyOutlined,
  FileTextOutlined,
  CalendarOutlined,
  ShoppingOutlined,
  RightOutlined,
} from '@ant-design/icons';
import { useEffect, useState, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useStatsData } from './useStatsData';
import { articleApi, type ArticleListItem } from '../../../api/health/articles';
import { useCountUp } from '../../../hooks/useCountUp';

export function OperatorDashboard() {
  const navigate = useNavigate();
  const { pointsStats, loading } = useStatsData();
  const [topArticles, setTopArticles] = useState<ArticleListItem[]>([]);
  const issuedCount = useCountUp(pointsStats?.total_issued ?? 0);
  const spentCount = useCountUp(pointsStats?.total_spent ?? 0);
  const activeCount = useCountUp(pointsStats?.active_accounts ?? 0);

  const fetchTopArticles = useCallback(async () => {
    try {
      const result = await articleApi.list({ status: 'published', page: 1, page_size: 5 });
      setTopArticles(result.data);
    } catch {
      // 静默降级
    }
  }, []);

  useEffect(() => { fetchTopArticles(); }, [fetchTopArticles]);

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

  return (
    <div>
      <Flex justify="space-between" align="center" style={{ marginBottom: 24 }}>
        <div>
          <Typography.Title level={4} style={{ margin: 0 }}>运营中心</Typography.Title>
          <Typography.Text type="secondary">积分、内容、活动</Typography.Text>
        </div>
      </Flex>

      <Row gutter={[16, 16]}>
        <Col xs={12} sm={6}>
          <Card size="small" style={{ cursor: 'pointer' }} onClick={() => navigate('/health/points')}>
            <Statistic title="积分发放" value={issuedCount} prefix={<TrophyOutlined />} />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small" style={{ cursor: 'pointer' }} onClick={() => navigate('/health/points')}>
            <Statistic title="积分消费" value={spentCount} prefix={<ShoppingOutlined />}
              suffix={pointsStats ? (
                <Typography.Text type="secondary" style={{ fontSize: 12 }}>
                  消费率{pointsStats.total_issued > 0 ? Math.round(pointsStats.total_spent / pointsStats.total_issued * 100) : 0}%
                </Typography.Text>
              ) : undefined}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small" style={{ cursor: 'pointer' }} onClick={() => navigate('/health/points')}>
            <Statistic title="活跃账户" value={activeCount} prefix={<FileTextOutlined />} />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small" style={{ cursor: 'pointer' }} onClick={() => navigate('/health/offline-events')}>
            <Statistic title="线下活动" value={0} prefix={<CalendarOutlined />} />
          </Card>
        </Col>

        {/* 积分排行 */}
        <Col xs={24} md={12}>
          <Card
            title="积分消费排行"
            size="small"
            extra={
              <Button type="link" size="small" icon={<RightOutlined />} onClick={() => navigate('/health/points')}>
                查看全部
              </Button>
            }
          >
            <List
              size="small"
              dataSource={pointsStats?.top_earners?.slice(0, 5) ?? []}
              locale={{ emptyText: '暂无数据' }}
              renderItem={(item, idx) => (
                <List.Item style={{ cursor: 'pointer' }} onClick={() => navigate(`/health/patients/${item.patient_id}`)}>
                  <Typography.Text>{idx + 1}. {item.patient_name}</Typography.Text>
                  <Typography.Text type="secondary">{item.total_earned} 分</Typography.Text>
                </List.Item>
              )}
            />
          </Card>
        </Col>

        {/* 热门文章 */}
        <Col xs={24} md={12}>
          <Card
            title="热门文章"
            size="small"
            extra={
              <Button type="link" size="small" icon={<RightOutlined />} onClick={() => navigate('/health/articles')}>
                内容管理
              </Button>
            }
          >
            <List
              size="small"
              dataSource={topArticles}
              locale={{ emptyText: '暂无数据' }}
              renderItem={(article) => (
                <List.Item style={{ padding: '6px 0', cursor: 'pointer' }} onClick={() => navigate(`/health/articles/edit/${article.id}`)}>
                  <Typography.Text ellipsis style={{ flex: 1, fontSize: 13 }}>{article.title}</Typography.Text>
                  <Typography.Text type="secondary" style={{ fontSize: 12, marginLeft: 8 }}>
                    {article.view_count} 次阅读
                  </Typography.Text>
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
}
