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

let settingsWindow: BrowserWindow | null = null;

export function createSettingsWindow(): BrowserWindow {
  if (settingsWindow) {
    log.info('Settings window already exists, focusing it');
    settingsWindow.focus();

    // Ensure dock icon is visible
    if (process.platform === 'darwin') {
      app.dock.show();
    }

    return settingsWindow;
  }

  // Show dock icon on macOS when settings window opens
  if (process.platform === 'darwin') {
    app.dock.show();
    log.info('Dock icon shown for settings');
  }

  settingsWindow = new BrowserWindow({
    width: 900,
    height: 650,
    minWidth: 800,
    minHeight: 500,
    resizable: true,
    minimizable: true,
    maximizable: true,
    fullscreenable: false,
    title: 'Instructure Agent - Settings',
    titleBarStyle: 'hiddenInset',
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: join(__dirname, '../preload/settings-preload.js')
    }
  });

  // Set Content Security Policy
  settingsWindow.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'"
        ]
      }
    });
  });

  // Load settings page
  // Check if Vite dev server is available (development mode with npm run dev)
  const isViteDevMode = !app.isPackaged && process.env.VITE_DEV_SERVER_URL;

  if (isViteDevMode) {
    // Development mode with npm run dev - load from Vite dev server
    const devServerURL = 'http://localhost:5173/settings/index.html';
    log.info(`Loading settings from Vite dev server: ${devServerURL}`);

    settingsWindow.loadURL(devServerURL).catch(err => {
      log.error('Failed to load URL:', err);
    });

    // Open DevTools in development
    settingsWindow.webContents.openDevTools();
  } else {
    // Production mode OR npm start - load from built files
    const rendererPath = join(__dirname, '../renderer/settings/index.html');
    log.info(`Loading settings from built files: ${rendererPath}`);
    settingsWindow.loadFile(rendererPath);

    // Open DevTools even in npm start mode for debugging
    if (!app.isPackaged) {
      settingsWindow.webContents.openDevTools();
    }
  }

  // Log any load failures
  settingsWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
    log.error('Settings window failed to load:', errorCode, errorDescription);
  });

  settingsWindow.on('closed', () => {
    log.info('Settings window closed');
    settingsWindow = null;

    // Hide dock icon on macOS if no other windows are open
    if (process.platform === 'darwin') {
      // Import window getters to check if any windows are still open
      const { getSetupWizardWindow } = require('./setup-wizard-window');
      const { getActionsWindow } = require('./actions-window');

      const setupWizardWindow = getSetupWizardWindow();
      const actionsWindow = getActionsWindow();

      // Only hide dock icon if all windows are closed
      if (!setupWizardWindow && !actionsWindow) {
        app.dock.hide();
        log.info('Dock icon hidden - all windows closed');
      }
    }
  });

  log.info('Settings window created');
  return settingsWindow;
}

export function showSettingsWindow(): void {
  if (settingsWindow) {
    settingsWindow.show();
    settingsWindow.focus();
  } else {
    createSettingsWindow();
  }
}
