import { useState, useEffect } from "react";
import {
  Drawer,
  Text,
  Loader,
  Center,
  ScrollArea,
  Group,
  Badge,
  Stack,
  Divider,
  ThemeIcon,
} from "@mantine/core";
import { healthStatus } from "../config/status";
import { apiRequest } from "../config/request";
import { EXTERNAL_API } from "../config/api";

// 子组件
import NodeConfigCard from "./NodeConfigCard";
import NodeLabelCard from "./NodeLabelCard";
import NodeMetaCard from "./NodeMetaCard";
import NodeHealthCard from "./NodeHealthCard";

export default function NodeDetailDrawer({ opened, nodeId, onClose }) {
  const [node, setNode] = useState(null);
  const [loading, setLoading] = useState(false);

  // 获取节点详情
  const fetchNodeDetail = async () => {
    if (!nodeId) return;
    setLoading(true);
    try {
      const res = await apiRequest(`${EXTERNAL_API.MASTER_NODES}/${nodeId}`);
      setNode(res);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (opened && nodeId) {
      fetchNodeDetail();
    }
  }, [opened, nodeId]);

  return (
    <Drawer
      opened={opened}
      onClose={onClose}
      position="right"
      size="lg"
      title="节点详情"
      padding="lg"
      overlayProps={{ backgroundOpacity: 0.4, blur: 4 }}
    >
      {loading ? (
  <Center h={200}>
    <Loader size="sm" />
  </Center>
) : node ? (
  <div style={{ height: '90vh', display: 'flex', flexDirection: 'column' }}>
    {/* 固定头部基础信息 */}
    <div style={{ position: 'sticky', top: 0, background: 'white', zIndex: 10, paddingBottom: 8 }}>
      <Group spacing="sm" align="center">
        <ThemeIcon
          size="lg"
          radius="xl"
          color={healthStatus(node.status).color}
          variant="light"
        >
          {healthStatus(node.status).icon}
        </ThemeIcon>

        <Text fw={700} size="xl">{node.name}</Text>
        <Badge color="gray">{node.type}</Badge>
        <Badge
          color={healthStatus(node.status).color}
          leftSection={healthStatus(node.status).icon}
        >
          {node.status}
        </Badge>
      </Group>
      <Divider my="sm" />
    </div>

    {/* 滚动内容 */}
    <ScrollArea style={{ flex: 1 }}>
      <Stack spacing="md">
        <NodeConfigCard node={node} onSaved={fetchNodeDetail} />
        <NodeLabelCard node={node} onSaved={fetchNodeDetail} />
        <NodeMetaCard node={node} />
        <NodeHealthCard node={node} />

        <Text c="dimmed" size="sm" ta="right">
          最后更新时间: {new Date(node.last_updated).toLocaleString()}
        </Text>
      </Stack>
    </ScrollArea>
  </div>
) : (
  <Text c="dimmed">暂无数据</Text>
)}
    </Drawer>
  );
}
