import { BrowserWindow, app, shell } from 'electron';
import { join } from 'path';
import log from 'electron-log';

let igniteAiWindow: BrowserWindow | null = null;

export function createIgniteAiWindow(): BrowserWindow {
  if (igniteAiWindow) {
    log.info('IgniteAI window already exists, focusing it');
    igniteAiWindow.focus();

    if (process.platform === 'darwin') {
      app.dock.show();
    }

    return igniteAiWindow;
  }

  if (process.platform === 'darwin') {
    app.dock.show();
    log.info('Dock icon shown for IgniteAI');
  }

  igniteAiWindow = new BrowserWindow({
    width: 900,
    height: 700,
    minWidth: 680,
    minHeight: 500,
    resizable: true,
    minimizable: true,
    maximizable: true,
    fullscreenable: true,
    title: 'IgniteAI',
    titleBarStyle: 'hiddenInset',
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: join(__dirname, '../preload/ignite-ai-preload.js'),
    }
  });

  // Open any links the chat widget spawns in the system browser, not a new BrowserWindow
  igniteAiWindow.webContents.setWindowOpenHandler(({ url }) => {
    log.info(`IgniteAI: opening external link in system browser: ${url}`);
    shell.openExternal(url);
    return { action: 'deny' };
  });

  // CSP: allow CDN assets and connections to the n8n instance
  igniteAiWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
    const csp = app.isPackaged
      ? [
          "default-src 'self' https://cdn.jsdelivr.net;",
          "script-src 'self' https://cdn.jsdelivr.net 'unsafe-inline' 'unsafe-eval';",
          "style-src 'self' https://cdn.jsdelivr.net 'unsafe-inline';",
          "connect-src 'self' https: wss:;",
          "img-src 'self' data: https: blob:;",
          "font-src 'self' data: https://cdn.jsdelivr.net;",
        ].join(' ')
      : [
          "default-src 'self' 'unsafe-inline' 'unsafe-eval'",
          "http://localhost:* ws://localhost:* https://cdn.jsdelivr.net https:;",
          "style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net;",
          "connect-src 'self' http://localhost:* ws://localhost:* https: wss:;",
          "img-src 'self' data: https: blob:;",
          "font-src 'self' data: https:;",
        ].join(' ');

    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': [csp],
      },
    });
  });

  const isViteDevMode = !app.isPackaged && process.env.VITE_DEV_SERVER_URL;

  if (isViteDevMode) {
    const devServerURL = 'http://localhost:5173/ignite-ai/index.html';
    log.info(`Loading IgniteAI from Vite dev server: ${devServerURL}`);
    igniteAiWindow.loadURL(devServerURL).catch((err) => {
      log.error('Failed to load IgniteAI URL:', err);
    });
  } else {
    const rendererPath = join(__dirname, '../renderer/ignite-ai/index.html');
    log.info(`Loading IgniteAI from built files: ${rendererPath}`);
    igniteAiWindow.loadFile(rendererPath);
  }

  igniteAiWindow.webContents.on('did-fail-load', (_event, errorCode, errorDescription) => {
    log.error('IgniteAI window failed to load:', errorCode, errorDescription);
  });

  igniteAiWindow.webContents.on('did-finish-load', () => {
    log.info('IgniteAI window finished loading');
    // igniteAiWindow?.webContents.openDevTools();
  });

  igniteAiWindow.webContents.on('console-message', (_event, _level, message) => {
    log.info(`[IgniteAI Console] ${message}`);
  });

  igniteAiWindow.on('closed', () => {
    log.info('IgniteAI window closed');
    igniteAiWindow = null;

    if (process.platform === 'darwin') {
      const { getActionsWindow } = require('./actions-window');
      const { getSetupWizardWindow } = require('./setup-wizard-window');
      const { getCareerWizardWindow } = require('./career-wizard-window');
      const { getBackupRestoreWindow } = require('./backup-restore-window');

      if (
        !getActionsWindow() &&
        !getSetupWizardWindow() &&
        !getCareerWizardWindow() &&
        !getBackupRestoreWindow()
      ) {
        app.dock.hide();
        log.info('Dock icon hidden - all windows closed');
      }
    }
  });

  log.info('IgniteAI window created');
  return igniteAiWindow;
}

export function showIgniteAiWindow(): void {
  if (igniteAiWindow) {
    igniteAiWindow.show();
    igniteAiWindow.focus();
  } else {
    createIgniteAiWindow();
  }
}

export function getIgniteAiWindow(): BrowserWindow | null {
  return igniteAiWindow;
}
