import { useState, useEffect } from "react";
import { Card, Text, Group, TextInput, Stack, ActionIcon } 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 NodeConfigCard({ nodeId, config = {}, onSaved }) {
  const [editing, setEditing] = useState(false);
  const [configList, setConfigList] = useState([]);
  const [newKey, setNewKey] = useState("");
  const [newValue, setNewValue] = useState("");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    const arr = Object.entries(config || {});
    setConfigList(arr);
  }, [config]);

  const removeConfig = (index) => {
    setConfigList((prev) => prev.filter((_, i) => i !== index));
  };

  const updateConfig = (index, key, value) => {
    setConfigList((prev) =>
      prev.map((item, i) => (i === index ? [key, value] : item))
    );
  };

  const addConfig = () => {
    if (newKey && !configList.find(([k]) => k === newKey)) {
      setConfigList((prev) => [...prev, [newKey, newValue]]);
      setNewKey("");
      setNewValue("");
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      let finalList = [...configList];
      // 如果有未点击“+”的新配置，补充进去
      if (newKey && !finalList.find(([k]) => k === newKey)) {
        finalList = [...finalList, [newKey, newValue]];
        setNewKey("");
        setNewValue("");
      }

      const configObj = Object.fromEntries(finalList);

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

      setConfigList(finalList); // 更新 state，保持 UI 同步
      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">
          {configList.map(([key, value], idx) => (
            <Group key={idx} spacing="xs">
              <TextInput
                placeholder="Key"
                value={key}
                onChange={(e) => updateConfig(idx, e.target.value, value)}
              />
              <TextInput
                placeholder="Value"
                value={value}
                onChange={(e) => updateConfig(idx, key, e.target.value)}
              />
              <ActionIcon color="red" onClick={() => removeConfig(idx)}>
                <IconTrash size={16} />
              </ActionIcon>
            </Group>
          ))}
          <Group spacing="xs">
            <TextInput
              placeholder="新增 Key"
              value={newKey}
              onChange={(e) => setNewKey(e.target.value)}
            />
            <TextInput
              placeholder="新增 Value"
              value={newValue}
              onChange={(e) => setNewValue(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  e.preventDefault();
                  addConfig();
                }
              }}
            />

            <ActionIcon color="blue" onClick={addConfig}>
              <IconPlus size={16} />
            </ActionIcon>
          </Group>
        </Stack>
      ) : (
        <Stack spacing="xs">
          {configList.length > 0 ? (
            configList.map(([key, value], idx) => (
              <Group key={idx} spacing="xs">
                <Text fw={500}>{key}:</Text>
                <Text>{String(value)}</Text>
              </Group>
            ))
          ) : (
            <Text c="dimmed">暂无配置</Text>
          )}
        </Stack>
      )}
    </Card>
  );
}
