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

let learnerHubWindow: BrowserWindow | null = null;

export function createLearnerHubWindow(): BrowserWindow {
  if (learnerHubWindow) {
    log.info('Learner Hub window already exists, focusing it');
    learnerHubWindow.focus();

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

    return learnerHubWindow;
  }

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

  const preloadPath = join(__dirname, '../preload/learner-hub-preload.js');

  learnerHubWindow = new BrowserWindow({
    width: 900,
    height: 720,
    minWidth: 800,
    minHeight: 720,
    resizable: true,
    minimizable: true,
    maximizable: true,
    fullscreenable: false,
    title: 'Learner Hub Setup',
    titleBarStyle: 'hiddenInset',
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: preloadPath
    }
  });

  learnerHubWindow.webContents.setWindowOpenHandler(({ url }) => {
    log.info(`Opening external link in system browser: ${url}`);
    shell.openExternal(url);
    return { action: 'deny' };
  });

  learnerHubWindow.webContents.session.webRequest.onHeadersReceived((details, callback) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': [
          app.isPackaged
            ? "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'"
            : "default-src 'self' 'unsafe-inline' 'unsafe-eval' http://localhost:* ws://localhost:*; style-src 'self' 'unsafe-inline'"
        ]
      }
    });
  });

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

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

    if (!app.isPackaged) {
      learnerHubWindow.webContents.openDevTools();
    }
  }

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

  learnerHubWindow.webContents.on('did-finish-load', () => {
    log.info('Learner Hub window finished loading');
  });

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

  learnerHubWindow.on('closed', () => {
    log.info('Learner Hub window closed');
    learnerHubWindow = null;

    const { checkStepsAndUpdateTrayIcon } = require('./index');
    checkStepsAndUpdateTrayIcon().catch((error: any) => {
      log.error('Error updating tray icon on window close:', error);
    });

    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');
      const { getIgniteAiWindow } = require('./ignite-ai-window');

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

  log.info('Learner Hub window created');
  return learnerHubWindow;
}

export function showLearnerHubWindow(): void {
  if (learnerHubWindow) {
    learnerHubWindow.show();
    learnerHubWindow.focus();
  } else {
    createLearnerHubWindow();
  }

  const { checkStepsAndUpdateTrayIcon } = require('./index');
  setTimeout(() => { checkStepsAndUpdateTrayIcon(); }, 500);
}

export function getLearnerHubWindow(): BrowserWindow | null {
  return learnerHubWindow;
}
