import { useEffect, useState, useMemo } from "react";
import { Stack, Title, Loader, Center, Group, Button, Badge, ActionIcon } from "@mantine/core";
import { IconRefresh } from "@tabler/icons-react";
import { apiRequest } from "../config/request";
import { EXTERNAL_API } from "../config/api";
import { AlertStats } from "../components/AlertStats";
import { AlertFilters } from "../components/AlertFilters";
import { AlertTable } from "../components/AlertTable";
import { formatRelativeTime } from "../config/utils";
import { EXTERNAL_HOST } from "../config/api";

export default function Alerts() {
  const [alerts, setAlerts] = useState([]);
  const [stats, setStats] = useState({ critical: 0, warning: 0, info: 0 });
  const [loading, setLoading] = useState(true);
  const [filters, setFilters] = useState({ severity: "all", state: "all", instance: "all" });
  const [page, setPage] = useState(1);
  const pageSize = 10;
  const [sortConfig, setSortConfig] = useState({ key: "startsAt", direction: "desc" });

  async function fetchAlerts() {
    setLoading(true);
    const data = await apiRequest(EXTERNAL_API.ALERTS_INFOS);
    if (data && Array.isArray(data)) {
      setAlerts(data);
      const counts = { critical: 0, warning: 0, info: 0 };
      data.forEach((alert) => {
        const sev = alert.labels?.severity || "info";
        if (sev === "critical") counts.critical++;
        else if (sev === "warning") counts.warning++;
        else counts.info++;
      });
      setStats(counts);
    }
    setLoading(false);
  }

  useEffect(() => {
    fetchAlerts();
    const timer = setInterval(fetchAlerts, 30000);
    return () => clearInterval(timer);
  }, []);

  // 节点选项
  const nodeOptions = useMemo(() => {
    const nodes = Array.from(new Set(alerts.map((a) => a.labels?.instance).filter(Boolean)));
    return [{ value: "all", label: "全部" }, ...nodes.map((n) => ({ value: n, label: n }))];
  }, [alerts]);

  // 过滤 & 排序 & 分页逻辑
  const filteredAlerts = useMemo(() => {
    return alerts.filter((alert) => {
      const sev = alert.labels?.severity || "info";
      const state = alert.status?.state || "active";
      const instance = alert.labels?.instance || "";
      return (
        (filters.severity === "all" || filters.severity === sev) &&
        (filters.state === "all" || filters.state === state) &&
        (filters.instance === "all" || filters.instance === instance)
      );
    });
  }, [alerts, filters]);

  const sortedAlerts = useMemo(() => {
    const sorted = [...filteredAlerts];
    if (sortConfig.key) {
      sorted.sort((a, b) => {
        let valA, valB;
        if (sortConfig.key === "severity") {
          const map = { critical: 3, warning: 2, info: 1 };
          valA = map[a.labels?.severity] || 0;
          valB = map[b.labels?.severity] || 0;
        } else if (["startsAt", "endsAt", "updatedAt"].includes(sortConfig.key)) {
          valA = new Date(a[sortConfig.key]).getTime() || 0;
          valB = new Date(b[sortConfig.key]).getTime() || 0;
        } else if (sortConfig.key === "instance") {
          valA = a.labels?.instance || "";
          valB = b.labels?.instance || "";
        } else {
          valA = a.labels?.alertname || "";
          valB = b.labels?.alertname || "";
        }
        if (valA < valB) return sortConfig.direction === "asc" ? -1 : 1;
        if (valA > valB) return sortConfig.direction === "asc" ? 1 : -1;
        return 0;
      });
    }
    return sorted;
  }, [filteredAlerts, sortConfig]);

  const paginatedAlerts = useMemo(() => {
    const start = (page - 1) * pageSize;
    return sortedAlerts.slice(start, start + pageSize);
  }, [sortedAlerts, page]);

  // 颜色 & Badge
  const getRowColor = (alert) => {
    if (alert.status?.state === "resolved") return "gray.1";
    const sev = alert.labels?.severity;
    if (sev === "critical") return "red.0";
    if (sev === "warning") return "orange.0";
    if (sev === "info") return "blue.0";
    return undefined;
  };
  const getSeverityColor = (sev) => {
    if (sev === "critical") return "red";
    if (sev === "warning") return "orange";
    if (sev === "info") return "blue";
    return "gray";
  };
  const getStateBadge = (state) => (
    <Badge color={state === "active" ? "red" : "gray"} variant="filled" size="xs">
      {state}
    </Badge>
  );
  const handleSort = (key) => {
    setSortConfig((prev) => ({
      key,
      direction: prev.key === key && prev.direction === "asc" ? "desc" : "asc",
    }));
  };

  return (
    <Stack spacing="lg" p="md">
      <Group position="apart">
        <Title order={2}>告警详情</Title>
        <Button component="a" href="{EXTERNAL_HOST.ALERTS}" target="_blank" variant="outline">
          打开 Alertmanager
        </Button>
        <ActionIcon onClick={fetchAlerts} color="blue" variant="filled" size="lg" title="刷新">
          <IconRefresh size={20} />
        </ActionIcon>
      </Group>

      <AlertStats stats={stats} />
      <AlertFilters filters={filters} setFilters={setFilters} nodeOptions={nodeOptions} />

      {loading ? (
        <Center>
          <Loader />
        </Center>
      ) : (
        <AlertTable
          alerts={alerts}
          paginatedAlerts={paginatedAlerts}
          page={page}
          setPage={setPage}
          pageSize={pageSize}
          sortedAlerts={sortedAlerts}
          sortConfig={sortConfig}
          handleSort={handleSort}
          getRowColor={getRowColor}
          getSeverityColor={getSeverityColor}
          getStateBadge={getStateBadge}
          formatRelativeTime={formatRelativeTime}
        />
      )}
    </Stack>
  );
}
