import type { ExtensionAPI } from "@jaeswift/jae-coding-agent";

export default function (pi: ExtensionAPI) {
  interface WidgetState {
    activeTool: string;
    lastToolDuration: number;
    errorsCount: number;
    warningsCount: number;
    lastActivity: string;
  }

  const state: WidgetState = {
    activeTool: "none",
    lastToolDuration: 0,
    errorsCount: 0,
    warningsCount: 0,
    lastActivity: "idle",
  };

  let toolStartTime = 0;

  function renderWidget(): string {
    const lines = [
      `\u{250C}\u{2500} JAE Status \u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2510}`,
      `\u{2502} Activity: ${state.lastActivity.padEnd(12)} \u{2502}`,
      `\u{2502} Tool:     ${state.activeTool.padEnd(12)} \u{2502}`,
      `\u{2502} Last:     ${(state.lastToolDuration + "ms").padEnd(12)} \u{2502}`,
      `\u{2502} Errors:   ${String(state.errorsCount).padEnd(12)} \u{2502}`,
      `\u{2514}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2518}`,
    ];
    return lines.join("\n");
  }

  function updateWidget(ctx: any): void {
    ctx.ui.setFooter("widget-demo", `\u{1F4DF} ${state.lastActivity} | Tool: ${state.activeTool} | Errs: ${state.errorsCount}`);
  }

  pi.on("tool_execution_start", async (event, ctx) => {
    toolStartTime = Date.now();
    state.activeTool = event.toolName || "unknown";
    state.lastActivity = "running";
    updateWidget(ctx);
  });

  pi.on("tool_execution_end", async (event, ctx) => {
    state.lastToolDuration = Date.now() - toolStartTime;
    state.activeTool = "none";
    state.lastActivity = "idle";

    // Check for errors in result
    const result = typeof event.result === "string" ? event.result : JSON.stringify(event.result);
    if (result.toLowerCase().includes("error")) {
      state.errorsCount++;
    }

    updateWidget(ctx);
  });

  pi.on("message_end", async (event, ctx) => {
    state.lastActivity = "thinking";
    updateWidget(ctx);
  });

  pi.on("turn_start", async (_event, ctx) => {
    state.lastActivity = "processing";
    updateWidget(ctx);
  });

  pi.on("turn_end", async (_event, ctx) => {
    state.lastActivity = "idle";
    updateWidget(ctx);
  });

  pi.registerCommand("widget", {
    description: "Show the JAE status widget demo",
    handler: async (_args, ctx) => {
      const widget = renderWidget();
      ctx.ui.notify(
        `\u{1F4DF} Widget API Demo:\n\n${widget}\n\nThis demonstrates how extensions can render live TUI widgets.\nThe footer bar shows real-time status updates.\n\nWidget State:\n  Active Tool: ${state.activeTool}\n  Last Duration: ${state.lastToolDuration}ms\n  Errors: ${state.errorsCount}\n  Activity: ${state.lastActivity}`,
        "info",
      );
    },
  });
}
