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

let backupRestoreWindow: BrowserWindow | null = null;

export function createBackupRestoreWindow(): BrowserWindow {
  if (backupRestoreWindow) {
    log.info('Backup/Restore window already exists, focusing it');
    backupRestoreWindow.focus();

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

    return backupRestoreWindow;
  }

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

  backupRestoreWindow = new BrowserWindow({
    width: 900,
    height: 720,
    minWidth: 800,
    minHeight: 720,
    resizable: true,
    minimizable: true,
    maximizable: true,
    fullscreenable: false,
    title: 'Backup / Restore',
    titleBarStyle: 'hiddenInset',
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: join(__dirname, '../preload/backup-restore-preload.js')
    }
  });

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

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

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

    backupRestoreWindow.webContents.openDevTools();
  } else {
    const rendererPath = join(__dirname, '../renderer/backup-restore/index.html');
    log.info(`Loading backup-restore from built files: ${rendererPath}`);
    backupRestoreWindow.loadFile(rendererPath);

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

  backupRestoreWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription) => {
    log.error('Backup/Restore window failed to load:', errorCode, errorDescription);
  });

  backupRestoreWindow.webContents.on('did-finish-load', () => {
    log.info('Backup/Restore window finished loading');
  });

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

  backupRestoreWindow.on('closed', () => {
    log.info('Backup/Restore window closed');
    backupRestoreWindow = null;

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

      const actionsWindow = getActionsWindow();
      const setupWizardWindow = getSetupWizardWindow();
      const careerWizardWindow = getCareerWizardWindow();
      const igniteAiWindow = getIgniteAiWindow();

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

  log.info('Backup/Restore window created');
  return backupRestoreWindow;
}

export function showBackupRestoreWindow(): void {
  if (backupRestoreWindow) {
    backupRestoreWindow.show();
    backupRestoreWindow.focus();
  } else {
    createBackupRestoreWindow();
  }
}

export function getBackupRestoreWindow(): BrowserWindow | null {
  return backupRestoreWindow;
}
