import { useState } from "react";
import { Card, Text, Group, TextInput, Stack, ActionIcon } from "@mantine/core";
import { IconEdit, IconX, IconCheck } from "@tabler/icons-react";
import { apiRequest } from "../config/request";
import { EXTERNAL_API } from "../config/api";

export default function NodeLabelCard({ node, onSaved }) {
  const [editing, setEditing] = useState(false);
  const [label, setLabel] = useState(node.label || {});
  const [saving, setSaving] = useState(false);

  const handleSave = async () => {
    setSaving(true);
    try {
      const res = await apiRequest(
        `${EXTERNAL_API.MASTER_NODES}/${node.id}`,
        {
          method: "PUT",
          body: JSON.stringify({ label }),
        },
        "标签已更新"
      );
      if (res) {
        setEditing(false);
        onSaved && onSaved();
      }
    } finally {
      setSaving(false);
    }
  };

  return (
    <Card shadow="sm" radius="md" withBorder>
      <Group position="apart" mb="sm">
        <Text fw={600}>标签信息</Text>
        <Group spacing="xs">
          {editing ? (
            <>
              <ActionIcon color="green" size="sm" loading={saving} onClick={handleSave}>
                <IconCheck size={16} />
              </ActionIcon>
              <ActionIcon color="red" size="sm" onClick={() => setEditing(false)}>
                <IconX size={16} />
              </ActionIcon>
            </>
          ) : (
            <ActionIcon color="blue" size="sm" onClick={() => setEditing(true)}>
              <IconEdit size={16} />
            </ActionIcon>
          )}
        </Group>
      </Group>

      {editing ? (
        <Stack>
          <TextInput
            label="标签"
            value={label.tag}
            onChange={(e) => setLabel({ ...label, tag: e.target.value })}
          />
        </Stack>
      ) : (
        <Text size="sm">标签: {label.tag}</Text>
      )}
    </Card>
  );
}
