import { useEffect, useState } from "react";
import { Grid, Text } from "@mantine/core";
import { ClusterTable } from "../components/DashboardNodeTable";
import { HealthCard } from "../components/HealthCard";
import { AlertCard } from "../components/AlertCard";
import { apiRequest } from "../config/request";
import { INTERNAL_API, EXTERNAL_API, EXTERNAL_HOST } 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);

    useEffect(() => {
        async function fetchData() {
            setLoading(true);
            try {
                const [clusterRes, healthRes, alertsRes] = await Promise.all([
                    apiRequest(EXTERNAL_API.MASTER_NODES),
                    apiRequest(INTERNAL_API.HEALTH),
                    apiRequest(INTERNAL_API.ALERTS),
                ]);

                setCluster({
                    total_nodes: clusterRes?.total || 0,
                    nodes: clusterRes?.data || [],
                });

                setHealth({
                    healthy_nodes: healthRes?.healthy_nodes || 0,
                    warning_nodes: healthRes?.warning_nodes || 0,
                    error_nodes: healthRes?.error_nodes || 0,
                });

                setAlerts({
                    total_alerts: alertsRes?.total_alerts || 0,
                    critical_alerts: alertsRes?.critical_alerts || 0,
                    major_alerts: alertsRes?.major_alerts || 0,
                    minor_alerts: alertsRes?.minor_alerts || 0,
                });
            } catch (err) {
                console.error("获取 Dashboard 数据失败:", err);
            } finally {
                setLoading(false);
            }
        }

        fetchData();
    }, []);

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

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

    return (
        <Grid>
            <Grid.Col span={12}><ClusterTable cluster={cluster} /></Grid.Col>
            <Grid.Col span={6}><HealthCard health={health} /></Grid.Col>
            <Grid.Col span={6}><AlertCard alerts={alerts} link={EXTERNAL_HOST.ALERTS} /></Grid.Col>
        </Grid>
    );
}
