/**
 * ETL 状态监控页面。
 *
 * - 游标状态 Table
 * - 最近执行记录 Table
 */

import React, { useEffect, useState, useCallback } from 'react';
import { Table, Tag, Button, message, Typography, Card, Row, Col, Statistic } from 'antd';
import { ReloadOutlined, DashboardOutlined, DatabaseOutlined, PlayCircleOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import {
  fetchCursors, fetchRecentRuns,
  type CursorInfo, type RecentRun,
} from '../api/etlStatus';

const { Title } = Typography;

const STATUS_COLOR: Record<string, string> = {
  success: 'green', failed: 'red', running: 'blue', cancelled: 'orange',
};

function formatTime(raw: string | null): string {
  if (!raw) return '—';
  const d = new Date(raw);
  return Number.isNaN(d.getTime()) ? raw : d.toLocaleString('zh-CN');
}

function formatDuration(ms: number | null): string {
  if (ms == null) return '—';
  if (ms < 1000) return `${ms}ms`;
  const seconds = Math.floor(ms / 1000);
  if (seconds < 60) return `${seconds}s`;
  const minutes = Math.floor(seconds / 60);
  const remainSec = seconds % 60;
  return `${minutes}m ${remainSec}s`;
}

const cursorColumns: ColumnsType<CursorInfo> = [
  { title: '任务编码', dataIndex: 'task_code', key: 'task_code', render: (v: string) => <code>{v}</code> },
  { title: '数据起始时间', dataIndex: 'last_start', key: 'last_start', render: (v: string | null) => formatTime(v) },
  { title: '数据截止时间', dataIndex: 'last_end', key: 'last_end', render: (v: string | null) => formatTime(v) },
];

const runColumns: ColumnsType<RecentRun> = [
  { title: '任务名称', dataIndex: 'task_codes', key: 'task_codes', render: (codes: string[]) => codes.join(', ') || '—' },
  {
    title: '状态', dataIndex: 'status', key: 'status', width: 90,
    render: (status: string) => <Tag color={STATUS_COLOR[status] ?? 'default'}>{status}</Tag>,
  },
  { title: '开始时间', dataIndex: 'started_at', key: 'started_at', width: 170, render: (v: string) => formatTime(v) },
  { title: '执行时长', dataIndex: 'duration_ms', key: 'duration_ms', width: 100, render: (v: number | null) => formatDuration(v) },
];

const ETLStatus: React.FC = () => {
  const [cursors, setCursors] = useState<CursorInfo[]>([]);
  const [runs, setRuns] = useState<RecentRun[]>([]);
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [c, r] = await Promise.all([fetchCursors(), fetchRecentRuns()]);
      setCursors(c);
      setRuns(r);
    } catch { message.error('加载 ETL 状态失败'); }
    finally { setLoading(false); }
  }, []);

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

  // 统计
  const successCount = runs.filter((r) => r.status === 'success').length;
  const failedCount = runs.filter((r) => r.status === 'failed').length;
  const runningCount = runs.filter((r) => r.status === 'running').length;

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={4} style={{ margin: 0 }}>
          <DashboardOutlined style={{ marginRight: 8 }} />
          ETL 状态监控
        </Title>
        <Button icon={<ReloadOutlined />} onClick={load} loading={loading}>刷新</Button>
      </div>

      {/* 统计卡片 */}
      <Row gutter={12} style={{ marginBottom: 16 }}>
        <Col span={6}>
          <Card size="small">
            <Statistic title="游标数" value={cursors.length} prefix={<DatabaseOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small">
            <Statistic title="最近执行" value={runs.length} prefix={<PlayCircleOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small">
            <Statistic title="成功" value={successCount} valueStyle={{ color: '#52c41a' }} />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small">
            <Statistic
              title="失败 / 运行中"
              value={failedCount}
              suffix={runningCount > 0 ? ` / ${runningCount}` : ''}
              valueStyle={{ color: failedCount > 0 ? '#ff4d4f' : undefined }}
            />
          </Card>
        </Col>
      </Row>

      <Card size="small" title="游标状态" style={{ marginBottom: 12 }}>
        <Table<CursorInfo>
          rowKey="task_code" columns={cursorColumns} dataSource={cursors}
          loading={loading} pagination={false} size="small"
        />
      </Card>

      <Card size="small" title="最近执行记录">
        <Table<RecentRun>
          rowKey="id" columns={runColumns} dataSource={runs}
          loading={loading} pagination={{ pageSize: 20, showTotal: (t) => `共 ${t} 条` }}
          size="small"
        />
      </Card>
    </div>
  );
};

export default ETLStatus;
