import { useState } from "react";
import { Card, Text, Stack, Group, ActionIcon, Badge, Popover } from "@mantine/core";
import { IconInfoCircle } from "@tabler/icons-react";


// 子组件：单条健康信息
function HealthItem({ moduleName, data }) {
  const status = data?.status || "unknown";
  const color = status === "healthy" ? "green" : status === "unhealthy" ? "red" : "gray";
  const [opened, setOpened] = useState(false);

  return (
    <Group key={moduleName} spacing="xs" align="center">
      <Text size="sm" fw={500}>{moduleName}</Text>
      <Badge color={color} variant="light">{status}</Badge>
      {(data?.error || data?.timestamp) && (
        <Popover
          opened={opened}
          onClose={() => setOpened(false)}
          position="bottom"
          withArrow
          shadow="sm"
        >
          <Popover.Target>
            <ActionIcon
              size="xs"
              color="blue"
              variant="light"
              onClick={() => setOpened((o) => !o)}
            >
              <IconInfoCircle size={14} />
            </ActionIcon>
          </Popover.Target>
          <Popover.Dropdown>
            <Stack spacing={4}>
              {data.error && <Text size="xs" c="red">Error: {data.error}</Text>}
              {data.timestamp && (
                <Text size="xs" c="dimmed">
                  Updated: {new Date(data.timestamp).toLocaleString()}
                </Text>
              )}
            </Stack>
          </Popover.Dropdown>
        </Popover>
      )}
    </Group>
  );
}

// 主组件：健康信息卡片
export default function NodeHealthCard({ node }) {
  const health = node.health || {};

  return (
    <Card shadow="xs" radius="md" withBorder>
      <Text fw={600} mb="sm">健康信息</Text>
      <Stack spacing="xs">
        {Object.entries(health).map(([moduleName, data]) => (
          <HealthItem key={moduleName} moduleName={moduleName} data={data} />
        ))}
      </Stack>
    </Card>
  );
}
