import { reactive, ref } from "vue";
import { apiRequest } from "../api";
import { useSessions } from "./useSessions";
import { useUI } from "./useUI";

const commandList = ref([]);
const commandLoading = ref(false);
const commandSaving = ref(false);
const commandError = ref("");
const commandEditingIndex = ref(-1);
const commandForm = reactive({ alias: "", command: "" });

async function loadCommands() {
  commandError.value = "";
  commandLoading.value = true;
  try {
    const res = await apiRequest("/commands", { method: "GET" });
    commandList.value = Array.isArray(res.data) ? res.data : [];
  } catch (err) {
    commandError.value = err.message || "加载快捷命令失败";
  } finally {
    commandLoading.value = false;
  }
}

function resetCommandForm() {
  commandEditingIndex.value = -1;
  commandForm.alias = "";
  commandForm.command = "";
}

function editCommand(item, index) {
  commandEditingIndex.value = index;
  commandForm.alias = item.alias || "";
  commandForm.command = item.command || "";
}

async function saveCommand() {
  commandError.value = "";
  if (!commandForm.alias || !commandForm.command) {
    commandError.value = "alias 和 command 为必填项";
    return;
  }
  commandSaving.value = true;
  try {
    const payload = { alias: commandForm.alias, command: commandForm.command };
    if (commandEditingIndex.value >= 0) {
      await apiRequest(`/commands/${commandEditingIndex.value}`, {
        method: "PUT", body: JSON.stringify(payload),
      });
    } else {
      await apiRequest("/commands", { method: "POST", body: JSON.stringify(payload) });
    }
    await loadCommands();
    resetCommandForm();
  } catch (err) {
    commandError.value = err.message || "保存快捷命令失败";
  } finally {
    commandSaving.value = false;
  }
}

async function deleteCommand(index) {
  commandError.value = "";
  try {
    await apiRequest(`/commands/${index}`, { method: "DELETE" });
    if (commandEditingIndex.value === index) resetCommandForm();
    await loadCommands();
  } catch (err) {
    commandError.value = err.message || "删除快捷命令失败";
  }
}

function applyCommandToTerminal(item) {
  const { sessions, activeId } = useSessions();
  const { closeOverlay } = useUI();
  const session = sessions.value.find((s) => s.id === activeId.value);
  if (!session?.ws || session.ws.readyState !== WebSocket.OPEN) {
    commandError.value = "当前没有可用终端连接";
    return;
  }
  const cmd = item.command || "";
  if (!cmd) return;
  session.ws.send(JSON.stringify({ type: "input", data: `${cmd}\n` }));
  closeOverlay();
}

export function useCommands() {
  return {
    commandList, commandLoading, commandSaving, commandError,
    commandEditingIndex, commandForm,
    loadCommands, resetCommandForm, editCommand, saveCommand,
    deleteCommand, applyCommandToTerminal,
  };
}
