import { ArrowRightOutlined, ReloadOutlined } from '@ant-design/icons';
import { Alert, Button, Card, Col, Flex, Row, Skeleton, Statistic, Typography } from 'antd';
import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router';
import { apiRequest } from '../api/http';
import { platformOperations } from '../api/platform-operations.generated';

const overviewOperation = platformOperations.find((operation) => operation.path === '/api/platform-admin/overview' && operation.method === 'GET');

const metricLabels: Record<string, string> = {
  tenantCount: '租户总数',
  activeTenantCount: '活跃租户',
  suspendedTenantCount: '暂停租户',
  activeSubscriptionCount: '有效订阅',
  overdueInvoiceCount: '逾期账单',
  outstandingAmountCents: '待收金额（分）',
  openAuditAlertCount: '未处理告警',
};

const workspaces = [
  { path: '/tenants', title: '租户管理', description: '租户创建、详情、域名、账务资料与生命周期' },
  { path: '/subscriptions', title: '套餐与订阅', description: 'SaaS 功能、限额、套餐版本与租户订阅' },
  { path: '/billing', title: '订单与发票', description: '服务费订单、退款、发票及交易记录' },
  { path: '/usage', title: '用量计费', description: '租户用量与超额计费数据' },
  { path: '/dunning', title: '收款与催缴', description: '人工收款、提醒渠道、通知事件与重试' },
  { path: '/question-banks', title: '公共题库', description: '题库目录、题目、导入与资源管理' },
  { path: '/crm', title: 'CRM 服务', description: '租户接入配置、线索队列与推送日志' },
  { path: '/sms', title: '短信服务', description: '渠道、模板审核与发送日志' },
  { path: '/payments', title: '支付服务', description: '支付应用、渠道、事件与返佣' },
  { path: '/staff', title: '员工与角色', description: '平台员工、角色和权限绑定' },
  { path: '/audit', title: '审计日志', description: '跨租户敏感操作检索' },
  { path: '/alerts', title: '审计告警', description: '安全告警确认、解决与忽略' },
];

export function DashboardPage() {
  const [data, setData] = useState<Record<string, unknown> | null>(null);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();
  const load = useCallback(async () => {
    if (!overviewOperation) return;
    setLoading(true);
    setError('');
    try {
      setData(await apiRequest<Record<string, unknown>>(overviewOperation));
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : '概览加载失败');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { void load(); }, [load]);
  const metrics = Object.entries(data || {}).filter(([, value]) => typeof value === 'number').slice(0, 8);
  return (
    <div className="dashboard-page">
      <Flex justify="space-between" align="end">
        <div>
          <Typography.Title level={2}>经营概览</Typography.Title>
          <Typography.Text type="secondary">平台运营、账务与安全状态</Typography.Text>
        </div>
        <Button icon={<ReloadOutlined />} onClick={() => void load()} loading={loading}>刷新</Button>
      </Flex>
      {error && <Alert type="error" showIcon message={error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
      <Skeleton loading={loading} active paragraph={{ rows: 4 }}>
        <Row gutter={[16, 16]}>
          {metrics.map(([key, value]) => (
            <Col xs={24} sm={12} xl={6} key={key}>
              <Card className="metric-card"><Statistic title={metricLabels[key] || key} value={value as number} /></Card>
            </Col>
          ))}
        </Row>
      </Skeleton>
      <Typography.Title level={4} className="dashboard-section-title">业务工作台</Typography.Title>
      <Row gutter={[16, 16]}>
        {workspaces.map((group) => (
          <Col xs={24} md={12} xl={8} key={group.path}>
            <Card hoverable className="portal-card" onClick={() => navigate(group.path)}>
              <Typography.Title level={5}>{group.title}</Typography.Title>
              <Typography.Paragraph type="secondary">{group.description}</Typography.Paragraph>
              <Button type="link" icon={<ArrowRightOutlined />} iconPosition="end">进入工作台</Button>
            </Card>
          </Col>
        ))}
      </Row>
    </div>
  );
}
