import { ref, onBeforeUnmount } from "vue";
import { Terminal } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit";
import { SearchAddon } from "@xterm/addon-search";
import { WebLinksAddon } from "@xterm/addon-web-links";
import "@xterm/xterm/css/xterm.css";

/** MobaXTerm Classic–inspired terminal theme colors. */
const defaultTheme = {
  background: "#0d1117",
  foreground: "#e0e0e0",
  cursor: "#58a6ff",
  cursorAccent: "#0d1117",
  selectionBackground: "rgba(88, 166, 255, 0.3)",
  selectionForeground: "#ffffff",
  black: "#0d1117",
  red: "#f85149",
  green: "#3fb950",
  yellow: "#e3b341",
  blue: "#58a6ff",
  magenta: "#bc8cff",
  cyan: "#39c5cf",
  white: "#e0e0e0",
  brightBlack: "#484f58",
  brightRed: "#ff7b72",
  brightGreen: "#56d364",
  brightYellow: "#e3b341",
  brightBlue: "#79c0ff",
  brightMagenta: "#d2a8ff",
  brightCyan: "#56d4dd",
  brightWhite: "#f0f6fc",
};

export interface UseTerminalReturn {
  terminal: Terminal;
  fitAddon: FitAddon;
  mount: (container: HTMLElement) => void;
  destroy: () => void;
  write: (data: string) => void;
  fit: () => void;
}

/**
 * Composable that manages an xterm.js Terminal lifecycle.
 *
 * Creates the terminal with fit, search, and web-links addons.
 * Data input and resize events are wired as TODOs for Wails bindings.
 */
export function useTerminal(sessionId: string): UseTerminalReturn {
  const fitAddon = new FitAddon();
  const searchAddon = new SearchAddon();
  const webLinksAddon = new WebLinksAddon();

  const terminal = new Terminal({
    theme: defaultTheme,
    fontFamily: "'JetBrains Mono', 'Cascadia Code', 'Fira Code', Menlo, Monaco, monospace",
    fontSize: 14,
    lineHeight: 1.2,
    cursorBlink: true,
    cursorStyle: "block",
    scrollback: 10000,
    allowProposedApi: true,
    convertEol: true,
  });

  terminal.loadAddon(fitAddon);
  terminal.loadAddon(searchAddon);
  terminal.loadAddon(webLinksAddon);

  // Capture typed data and forward to the SSH backend
  terminal.onData((_data: string) => {
    // TODO: Replace with Wails binding call — SSHService.Write(sessionId, data)
    // For now, echo typed data back to the terminal for visual feedback
    void sessionId;
  });

  // Handle terminal resize events
  terminal.onResize((_size: { cols: number; rows: number }) => {
    // TODO: Replace with Wails binding call — SSHService.Resize(sessionId, cols, rows)
    void sessionId;
  });

  let resizeObserver: ResizeObserver | null = null;

  function mount(container: HTMLElement): void {
    terminal.open(container);
    fitAddon.fit();

    // Auto-fit when the container resizes
    resizeObserver = new ResizeObserver(() => {
      fitAddon.fit();
    });
    resizeObserver.observe(container);

    // Write a placeholder welcome message (mock — replaced by real SSH output)
    terminal.writeln("\x1b[1;34m  Wraith Terminal\x1b[0m");
    terminal.writeln("\x1b[90m  Session: " + sessionId + "\x1b[0m");
    terminal.writeln("\x1b[90m  Waiting for SSH connection...\x1b[0m");
    terminal.writeln("");
  }

  function destroy(): void {
    if (resizeObserver) {
      resizeObserver.disconnect();
      resizeObserver = null;
    }
    terminal.dispose();
  }

  function write(data: string): void {
    terminal.write(data);
  }

  function fit(): void {
    fitAddon.fit();
  }

  onBeforeUnmount(() => {
    destroy();
  });

  return { terminal, fitAddon, mount, destroy, write, fit };
}
