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

let setupWizardWindow: BrowserWindow | null = null;

export function createSetupWizardWindow(): BrowserWindow {
  if (setupWizardWindow) {
    log.info('Setup wizard window already exists, focusing it');
    setupWizardWindow.focus();

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

    return setupWizardWindow;
  }

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

  const preloadPath = join(__dirname, '../preload/setup-wizard-preload.js');
  const fs = require('fs');
  log.info(`Setup 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}`);
  }

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

  // Handle external links - open in system's default browser
  setupWizardWindow.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
  setupWizardWindow.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' 'unsafe-inline'"
            : "default-src 'self' 'unsafe-inline' 'unsafe-eval' http://localhost:* ws://localhost:*; style-src 'self' 'unsafe-inline'"
        ]
      }
    });
  });

  // Load setup-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/setup-wizard/index.html';
    log.info(`Loading setup-wizard from Vite dev server: ${devServerURL}`);

    setupWizardWindow.loadURL(devServerURL).catch(err => {
      log.error('Failed to load setup-wizard URL:', err);
    });
  } else {
    // Production mode OR npm start - load from built files
    const rendererPath = join(__dirname, '../renderer/setup-wizard/index.html');
    log.info(`Loading setup-wizard from built files: ${rendererPath}`);
    setupWizardWindow.loadFile(rendererPath);
  }

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

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

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

  setupWizardWindow.on('closed', () => {
    log.info('Setup wizard window closed');
    setupWizardWindow = 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 actionsWindow = getActionsWindow();

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

  log.info('Setup wizard window created');
  return setupWizardWindow;
}

export function showSetupWizardWindow(): void {
  if (setupWizardWindow) {
    setupWizardWindow.show();
    setupWizardWindow.focus();
  } else {
    createSetupWizardWindow();
  }

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

export function getSetupWizardWindow(): BrowserWindow | null {
  return setupWizardWindow;
}
