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

export default function NodeLabelCard({ nodeId, labels = [], onSaved }) {
  const [editing, setEditing] = useState(false);
  const [tagList, setTagList] = useState([]);
  const [tagColors, setTagColors] = useState([]);
  const [newTag, setNewTag] = useState("");
  const [saving, setSaving] = useState(false);

  const randomColor = () => {
    const colors = ["red", "pink", "grape", "violet", "indigo", "blue", "cyan", "teal", "green", "lime", "yellow", "orange", "gray"];
    return colors[Math.floor(Math.random() * colors.length)];
  };

  useEffect(() => {
    const arr = Array.isArray(labels) ? labels : [];
    setTagList(arr);
    setTagColors(arr.map(() => randomColor()));
  }, [labels]);

  const removeTag = (index) => {
    setTagList((prev) => prev.filter((_, i) => i !== index));
    setTagColors((prev) => prev.filter((_, i) => i !== index));
  };

  const updateTag = (index, value) => {
    setTagList((prev) => prev.map((t, i) => (i === index ? value : t)));
  };

  const addTag = () => {
    if (newTag && !tagList.includes(newTag)) {
      setTagList((prev) => [...prev, newTag]);
      setTagColors((prev) => [...prev, randomColor()]);
      setNewTag("");
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      let finalTags = [...tagList];
      if (newTag && !finalTags.includes(newTag)) {
        finalTags = [...finalTags, newTag];
        setNewTag(""); // 清空输入框
      }

      await apiRequest(MASTER_API.CONFIG(nodeId), {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ label: finalTags }),
      });

      setTagList(finalTags);
      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 spacing="xs">
          {tagList.map((tag, idx) => (
            <Group key={idx} spacing="xs">
              <TextInput value={tag} onChange={(e) => updateTag(idx, e.target.value)} />
              <ActionIcon color="red" onClick={() => removeTag(idx)}><IconTrash size={16} /></ActionIcon>
            </Group>
          ))}
          <Group spacing="xs">
            <TextInput
              placeholder="新增标签"
              value={newTag}
              onChange={(e) => setNewTag(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  e.preventDefault(); // 阻止默认提交行为
                  addTag();
                }
              }}
            />

            <ActionIcon color="blue" onClick={addTag}><IconPlus size={16} /></ActionIcon>
          </Group>
        </Stack>
      ) : (
        <Group spacing="xs" wrap="wrap">
          {tagList.length > 0 ? tagList.map((tag, idx) => (
            <Badge key={idx} color={tagColors[idx]} variant="light">{tag}</Badge>
          )) : <Text c="dimmed">暂无标签</Text>}
        </Group>
      )}
    </Card>
  );
}
