/**
 * 运行状态仪表盘（Dashboard）
 *
 * 登录后默认首页，聚合 4 个区块：
 * 1. OpsPanel 子组件（系统资源、服务状态、Git 状态）
 * 2. 数据库健康监控（DbHealthCard）
 * 3. AI 运行总览（复用 AIDashboard）
 * 4. AI 调度摘要（今日触发数、成功率、最近错误 + 跳转链接）
 *
 * 跳转链接：
 * - "ETL 状态详情" → /etl-tasks?tab=status
 * - "触发器详情"   → /triggers?tab=all
 * - "AI 调度详情"  → /triggers?tab=ai
 *
 * _Requirements: 2.1, 2.2, 2.6, 2.7, 2.8, 7.1, 7.2_
 */

import React, { useEffect, useState, useCallback } from "react";
import {
  Typography,
  Spin,
  message,
  Modal,
  Card,
  Row,
  Col,
  Statistic,
  Tag,
  Button,
  Space,
  Divider,
  List,
} from "antd";
import {
  DashboardOutlined,
  ReloadOutlined,
  RightOutlined,
  CloseCircleOutlined,
  ThunderboltOutlined,
} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import type { SystemInfo, ServiceStatus, GitInfo } from "../api/opsPanel";
import {
  fetchSystemInfo,
  fetchServicesStatus,
  fetchGitInfo,
  startService,
  stopService,
  restartService,
  gitPull,
  syncDeps,
} from "../api/opsPanel";
import {
  SystemResourceSection,
  ServiceStatusSection,
  GitStatusSection,
} from "../components/ops";
import { fetchDbHealth } from "../api/dbHealth";
import type { DbHealthItem } from "../api/dbHealth";
import DbHealthCard from "../components/DbHealthCard";
import AIDashboard from "./AIDashboard";
import { getTriggerJobs, type TriggerJobItem } from "../api/adminAI";

const { Title, Text } = Typography;

/* 超时阈值（毫秒） */
const DB_HEALTH_TIMEOUT = 10_000;

const Dashboard: React.FC = () => {
  const navigate = useNavigate();

  // ---- OpsPanel 数据 ----
  const [system, setSystem] = useState<SystemInfo | null>(null);
  const [services, setServices] = useState<ServiceStatus[]>([]);
  const [gitInfos, setGitInfos] = useState<GitInfo[]>([]);
  const [opsLoading, setOpsLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState<Record<string, boolean>>({});

  // ---- DB 健康数据 ----
  const [dbItems, setDbItems] = useState<DbHealthItem[]>([]);
  const [dbLoading, setDbLoading] = useState(true);
  const [dbTimeout, setDbTimeout] = useState(false);

  // ---- AI 调度摘要 ----
  const [triggerItems, setTriggerItems] = useState<TriggerJobItem[]>([]);
  const [triggerTotal, setTriggerTotal] = useState(0);
  const [triggerLoading, setTriggerLoading] = useState(true);

  // ---- OpsPanel 数据加载（复用 OpsPanel.tsx 逻辑） ----

  const loadOps = useCallback(async () => {
    try {
      const [sys, svc, git] = await Promise.all([
        fetchSystemInfo(),
        fetchServicesStatus(),
        fetchGitInfo(),
      ]);
      setSystem(sys);
      setServices(svc);
      setGitInfos(git);
    } catch {
      message.error("加载运维数据失败");
    } finally {
      setOpsLoading(false);
    }
  }, []);

  // ---- DB 健康加载 ----

  const loadDbHealth = useCallback(async () => {
    setDbLoading(true);
    setDbTimeout(false);
    const timer = setTimeout(() => {
      setDbTimeout(true);
      setDbLoading(false);
    }, DB_HEALTH_TIMEOUT);
    try {
      const items = await fetchDbHealth();
      clearTimeout(timer);
      setDbItems(items);
      setDbTimeout(false);
    } catch {
      clearTimeout(timer);
      message.error("加载数据库健康数据失败");
    } finally {
      setDbLoading(false);
    }
  }, []);

  // ---- AI 调度摘要加载 ----

  const loadTriggerSummary = useCallback(async () => {
    setTriggerLoading(true);
    try {
      const res = await getTriggerJobs({ page: 1, page_size: 50 });
      setTriggerItems(res.items);
      setTriggerTotal(res.total);
    } catch {
      message.error("加载 AI 调度数据失败");
    } finally {
      setTriggerLoading(false);
    }
  }, []);

  // ---- 初始化 + 定时刷新 ----

  useEffect(() => {
    loadOps();
    loadDbHealth();
    loadTriggerSummary();
    const timer = setInterval(loadOps, 15_000);
    return () => clearInterval(timer);
  }, [loadOps, loadDbHealth, loadTriggerSummary]);

  // ---- OpsPanel 操作处理（复用 OpsPanel.tsx 逻辑） ----

  const withAction = async (key: string, fn: () => Promise<void>) => {
    setActionLoading((prev) => ({ ...prev, [key]: true }));
    try {
      await fn();
    } finally {
      setActionLoading((prev) => ({ ...prev, [key]: false }));
    }
  };

  const handleStart = (env: string) =>
    withAction(`start-${env}`, async () => {
      const r = await startService(env);
      r.success ? message.success(r.message) : message.warning(r.message);
      await loadOps();
    });

  const handleStop = (env: string) =>
    withAction(`stop-${env}`, async () => {
      const r = await stopService(env);
      r.success ? message.success(r.message) : message.warning(r.message);
      await loadOps();
    });

  const handleRestart = (env: string) =>
    withAction(`restart-${env}`, async () => {
      const r = await restartService(env);
      r.success ? message.success(r.message) : message.warning(r.message);
      await loadOps();
    });

  const handlePull = (env: string) =>
    withAction(`pull-${env}`, async () => {
      const r = await gitPull(env);
      if (r.success) {
        message.success("拉取成功");
        Modal.info({
          title: `Git Pull - ${env}`,
          content: (
            <pre style={{ maxHeight: 300, overflow: "auto", fontSize: 12 }}>
              {r.output}
            </pre>
          ),
          width: 600,
        });
      } else {
        message.error("拉取失败");
        Modal.error({
          title: `Git Pull 失败 - ${env}`,
          content: (
            <pre style={{ maxHeight: 300, overflow: "auto", fontSize: 12 }}>
              {r.output}
            </pre>
          ),
          width: 600,
        });
      }
      await loadOps();
    });

  const handleSyncDeps = (env: string) =>
    withAction(`sync-${env}`, async () => {
      const r = await syncDeps(env);
      r.success ? message.success("依赖同步完成") : message.error(r.message);
    });

  // ---- AI 调度摘要计算 ----

  const todayStr = new Date().toISOString().slice(0, 10);
  const todayJobs = triggerItems.filter(
    (j) => j.created_at && j.created_at.startsWith(todayStr),
  );
  const todayCount = todayJobs.length;
  const todaySuccess = todayJobs.filter((j) => j.status === "success").length;
  const todaySuccessRate =
    todayCount > 0 ? ((todaySuccess / todayCount) * 100).toFixed(1) : "0.0";
  const recentErrors = triggerItems
    .filter((j) => j.status === "failed")
    .slice(0, 5);

  // ---- 渲染 ----

  if (opsLoading) {
    return (
      <Spin
        size="large"
        style={{ display: "flex", justifyContent: "center", marginTop: 120 }}
      />
    );
  }

  return (
    <div>
      {/* 页面标题 + 快捷跳转 */}
      <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
        <Title level={4} style={{ margin: 0 }}>
          <DashboardOutlined style={{ marginRight: 8 }} />
          运行状态
        </Title>
        <Space>
          <Button size="small" onClick={() => navigate("/etl-tasks?tab=status")}>
            ETL 状态详情 <RightOutlined />
          </Button>
          <Button size="small" onClick={() => navigate("/triggers?tab=all")}>
            触发器详情 <RightOutlined />
          </Button>
          <Button size="small" onClick={() => navigate("/triggers?tab=ai")}>
            AI 调度详情 <RightOutlined />
          </Button>
        </Space>
      </Row>

      {/* 区块 1：OpsPanel 子组件 */}
      {system && <SystemResourceSection system={system} />}

      <ServiceStatusSection
        services={services}
        actionLoading={actionLoading}
        onStart={handleStart}
        onStop={handleStop}
        onRestart={handleRestart}
      />

      <GitStatusSection
        gitInfos={gitInfos}
        services={services}
        actionLoading={actionLoading}
        onPull={handlePull}
        onSyncDeps={handleSyncDeps}
      />

      {/* 区块 2：数据库健康监控 */}
      <DbHealthCard
        items={dbItems}
        loading={dbLoading}
        timeout={dbTimeout}
        onRetry={loadDbHealth}
      />

      {/* 区块 3：AI 运行总览（复用 AIDashboard） */}
      <Divider orientation="left">AI 运行总览</Divider>
      <AIDashboard />

      {/* 区块 4：AI 调度摘要 */}
      <Divider orientation="left">AI 调度摘要</Divider>
      <Card
        size="small"
        title={
          <Space>
            <ThunderboltOutlined />
            <span>AI 调度摘要</span>
          </Space>
        }
        extra={
          <Button
            size="small"
            icon={<ReloadOutlined />}
            onClick={loadTriggerSummary}
            loading={triggerLoading}
          >
            刷新
          </Button>
        }
        style={{ marginBottom: 16 }}
      >
        {/* 统计卡片行 */}
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={8}>
            <Statistic title="今日触发数" value={todayCount} />
          </Col>
          <Col span={8}>
            <Statistic title="今日成功率" value={todaySuccessRate} suffix="%" />
          </Col>
          <Col span={8}>
            <Statistic
              title="总记录数"
              value={triggerTotal}
              valueStyle={{ fontSize: 16 }}
            />
          </Col>
        </Row>

        {/* 最近错误列表 */}
        <Card type="inner" size="small" title="最近错误" style={{ marginBottom: 12 }}>
          {recentErrors.length === 0 ? (
            <Text type="secondary">暂无失败记录</Text>
          ) : (
            <List
              size="small"
              dataSource={recentErrors}
              renderItem={(item) => (
                <List.Item>
                  <Space>
                    <CloseCircleOutlined style={{ color: "#ff4d4f" }} />
                    <Tag color="error">{item.status}</Tag>
                    <Text>{item.event_type}</Text>
                    <Text type="secondary" style={{ fontSize: 12 }}>
                      ID: {item.id}
                    </Text>
                    <Text type="secondary" style={{ fontSize: 12 }}>
                      {item.created_at
                        ? new Date(item.created_at).toLocaleString("zh-CN")
                        : "—"}
                    </Text>
                  </Space>
                </List.Item>
              )}
            />
          )}
        </Card>

        {/* 跳转链接 */}
        <Button
          type="link"
          onClick={() => navigate("/triggers?tab=ai")}
          style={{ padding: 0 }}
        >
          查看 AI 调度详情 <RightOutlined />
        </Button>
      </Card>
    </div>
  );
};

export default Dashboard;
