import { useEffect, useState } from "react";
import { Grid, Text, Stack, Title } from "@mantine/core";
import { NodeTable } from "../components/NodeTable";
import { HealthCard } from "../components/HealthCard";
import { AlertStats } from "../components/AlertStats";
import { apiRequest } from "../config/request";
import { EXTERNAL_API } from "../config/api";
import { MASTER_API } from "../config/api";

export default function Dashboard() {
    const [cluster, setCluster] = useState(null);
    const [health, setHealth] = useState(null);
    const [alerts, setAlerts] = useState(null);
    const [loading, setLoading] = useState(true);

    const countAlerts = (data) => {
        const stats = { critical: 0, warning: 0, info: 0, total: 0 };
        data?.forEach((alert) => {
            const severity = alert.labels?.severity || "info";
            if (severity === "critical") stats.critical++;
            else if (severity === "warning") stats.warning++;
            else stats.info++;
            stats.total++;
        });
        return stats;
    };

    useEffect(() => {
        async function fetchData() {
            setLoading(true);
            try {
                const [clusterRes, healthRes, alertsRes] = await Promise.all([
                    apiRequest(MASTER_API.LIST),
                    apiRequest(MASTER_API.STATISTICS),
                    apiRequest(EXTERNAL_API.ALERTS_INFOS),
                ]);

                setCluster(clusterRes || []);

                setHealth({
                    total: healthRes?.total || 0,
                    status_statistics: healthRes?.status_statistics || [],
                });

                setAlerts(countAlerts(alertsRes || []));
            } catch (err) {
                console.error("获取 Dashboard 数据失败:", err);
            } finally {
                setLoading(false);
            }
        }

        fetchData();
    }, []);

    if (loading) {
        return <Text>加载中...</Text>;
    }

    if (!cluster || !health || !alerts) {
        return <Text>数据加载失败</Text>;
    }

    return (
        <Stack spacing="lg" p="md">
            <Title order={1} mb="md">仪表盘</Title>
            <Grid>

                <Grid.Col span={6}><HealthCard health={health} /></Grid.Col>
                <Grid.Col span={6}>
                    <AlertStats stats={alerts} layout="column" title="告警统计" link="/alerts" />
                </Grid.Col>
                <Grid.Col span={12}><NodeTable clusterData={cluster} title="集群节点" viewMoreLink="/nodeInfo" /></Grid.Col>
            </Grid>
        </Stack>
    );
}
