import GameDataManager from "./GameDataManager";

class ConsoleManager {
  constructor() {
    this.commands = ["/clear", "/give", "/set_exp"];
    this.logs = ["[System] Console Manager Ready. Press F9 to hide."];
    this.history = [];
    this.historyIndex = -1;
    this.onLogsChange = null;
    this.socket = null;
  }

  init(socket, onLogsChange) {
    this.socket = socket;
    this.onLogsChange = onLogsChange;

    if (this.socket) {
      this.socket.off("admin:log");
      this.socket.on("admin:log", (msg) => this.addLog(`[Server] ${msg}`));
    }
  }

  addLog(line) {
    this.logs = [...this.logs.slice(-100), line];
    if (this.onLogsChange) this.onLogsChange(this.logs);
  }

  getSuggestions(input, players = []) {
    const safePlayers = (players || []).filter((p) => typeof p === "string");

    const parts = input.split(" ");
    if (parts.length === 0) return [];

    const cmd = parts[0].toLowerCase();

    if (parts.length === 1 && input.startsWith("/")) {
      return this.commands.filter((c) => c.startsWith(cmd));
    }

    if (cmd === "/give") {
      if (parts.length === 2) {
        const search = parts[1].toLowerCase();
        return safePlayers.filter((p) => p.toLowerCase().startsWith(search));
      }
      if (parts.length === 3) {
        const search = parts[2].toLowerCase();
        const itemIds = Array.from(GameDataManager.items.keys());
        return itemIds
          .filter((id) => id.toLowerCase().includes(search))
          .slice(0, 15);
      }
    }

    if (cmd === "/set_exp") {
      if (parts.length === 2) {
        const search = parts[1].toLowerCase();
        return safePlayers.filter((p) => p.toLowerCase().startsWith(search));
      }
    }

    if (cmd === "/clear" && parts.length === 2) {
      const search = parts[1].toLowerCase();
      return safePlayers.filter((p) => p.toLowerCase().startsWith(search));
    }

    return [];
  }
  execute(input) {
    const trimmed = input.trim();
    if (!trimmed) return;

    this.addLog(`> ${trimmed}`);

    if (this.history[0] !== trimmed) {
      this.history.unshift(trimmed);
      if (this.history.length > 50) this.history.pop();
    }
    this.historyIndex = -1;

    if (this.socket) {
      this.socket.emit("admin:command", { command: trimmed });
    }
  }

  getHistory(direction) {
    if (this.history.length === 0) return null;

    if (direction === "up") {
      this.historyIndex = Math.min(
        this.historyIndex + 1,
        this.history.length - 1,
      );
    } else {
      this.historyIndex = Math.max(this.historyIndex - 1, -1);
    }

    return this.historyIndex === -1 ? "" : this.history[this.historyIndex];
  }
}

export default new ConsoleManager();
