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

let careerWizardWindow: BrowserWindow | null = null;

export function createCareerWizardWindow(): BrowserWindow {
  if (careerWizardWindow) {
    log.info('Career wizard window already exists, focusing it');
    careerWizardWindow.focus();

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

    return careerWizardWindow;
  }

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

  const preloadPath = join(__dirname, '../preload/career-wizard-preload.js');
  const fs = require('fs');
  log.info(`Career wizard preload path: ${preloadPath}`);
  log.info(`Preload file exists: ${fs.existsSync(preloadPath)}`);
  if (fs.existsSync(preloadPath)) {
    const stats = fs.statSync(preloadPath);
    log.info(`Preload file size: ${stats.size} bytes`);
    log.info(`Preload file modified: ${stats.mtime}`);
  }

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

  // Handle external links - open in system's default browser
  careerWizardWindow.webContents.setWindowOpenHandler(({ url }) => {
    log.info(`Opening external link in system browser: ${url}`);

    // Open in system's default browser (Safari, Chrome, etc.)
    shell.openExternal(url);

    // Deny creating a new Electron window
    return { action: 'deny' };
  });

  // Set Content Security Policy
  careerWizardWindow.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 career-wizard 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/career-wizard/index.html';
    log.info(`Loading career-wizard from Vite dev server: ${devServerURL}`);

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

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

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

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

  // Log when preload script finishes
  careerWizardWindow.webContents.on('did-finish-load', () => {
    log.info('Career wizard window finished loading');
  });

  // Log console messages from preload
  careerWizardWindow.webContents.on('console-message', (event, level, message, line, sourceId) => {
    log.info(`[Renderer Console] ${message}`);
  });

  careerWizardWindow.on('closed', () => {
    log.info('Career wizard window closed');
    careerWizardWindow = null;

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

    // 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 { getActionsWindow } = require('./actions-window');
      const { getSetupWizardWindow } = require('./setup-wizard-window');

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

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

  log.info('Career wizard window created');
  return careerWizardWindow;
}

export function showCareerWizardWindow(): void {
  if (careerWizardWindow) {
    careerWizardWindow.show();
    careerWizardWindow.focus();
  } else {
    createCareerWizardWindow();
  }

  // Check steps and update tray icon when window is shown
  const { checkStepsAndUpdateTrayIcon } = require('./index');
  setTimeout(() => {
    checkStepsAndUpdateTrayIcon();
  }, 500);
}

export function getCareerWizardWindow(): BrowserWindow | null {
  return careerWizardWindow;
}
