import { Menu, app, MenuItemConstructorOptions, nativeImage, dialog, shell } from 'electron';
import { join } from 'path';
import log from 'electron-log';
import { showSetupWizardWindow } from './setup-wizard-window';
import { showCareerWizardWindow } from './career-wizard-window';
import { showBackupRestoreWindow } from './backup-restore-window';
import { showIgniteAiWindow } from './ignite-ai-window';
import { showLearnerHubWindow } from './learner-hub-window';
import { showActionsWindow } from './actions-window';
import { showSettingsWindow } from './settings-window';
import { checkForUpdates } from './updater';
import { getInstDomain } from './services/inst-config-manager';
import { checkFrpcConfigStatus } from './services/frpc-config-manager';
import { execAsync } from './utils/shell-utils';

async function getRunningCanvasContainers(): Promise<string[]> {
  try {
    const { stdout } = await execAsync(
      `{
        {
          docker ps -a --filter "name=.*canvas-" --format "{{.Labels}}" | tr ',' '\n' | grep "traefik\.http\..*\.service" | cut -d'=' -f2
          docker ps -a --filter "name=.*canvas-" --format "{{.Names}}"
        } | sort -u | grep -E "canvas-pgadmin|term|^canvas-web$|^canvas-web-.*" | grep -vE "canvas-web-dev-logs" 
        {
          docker ps -a --filter "name=.*canvas-" --format "{{.Labels}}" | tr ',' '\n' | grep "traefik\.http\..*\.service" | cut -d'=' -f2
          docker ps -a --filter "name=.*canvas-" --format "{{.Names}}"
        } | sort -u | grep -E "canvas-web-dev-logs-term"
        } | sort -u `
    );
    return stdout
      .split('\n')
      .map(name => name.trim())
      .filter(name => name.length > 0);
  } catch {
    return [];
  }
}

function showAboutDialog(): void {
  const version = app.getVersion();

  dialog.showMessageBox({
    type: 'info',
    title: 'About Instructure Agent',
    message: 'Instructure Agent',
    detail: `Version ${version}\n\n© ${new Date().getFullYear()} Instructure`,
    buttons: ['OK']
  });
}

export async function createMenu(onOpen: () => void): Promise<Menu> {
  // Load canvas icon for menu
  const canvasIconPath = join(__dirname, '../assets/icons/tray-canvas-orange-icon.png');
  const canvasIcon = nativeImage.createFromPath(canvasIconPath);
  const resizedCanvasIcon = canvasIcon.resize({ width: 16, height: 16 });

  // Load traefik icon for menu
  const traefikIconPath = join(__dirname, '../assets/icons/traefik-icon.png');
  const traefikIcon = nativeImage.createFromPath(traefikIconPath);
  const resizedTraefikIcon = traefikIcon.resize({ width: 16, height: 16 });

  // Load dozzle icon for menu
  const dozzleIconPath = join(__dirname, '../assets/icons/dozzle-icon.png');
  const dozzleIcon = nativeImage.createFromPath(dozzleIconPath);
  const resizedDozzleIcon = dozzleIcon.resize({ width: 16, height: 16 });

  // Load canvas actions icon for menu
  const canvasActionsIconPath = join(__dirname, '../assets/icons/canvas-actions-icon.png');
  const canvasActionsIcon = nativeImage.createFromPath(canvasActionsIconPath);
  const resizedCanvasActionsIcon = canvasActionsIcon.resize({ width: 16, height: 16 });

  // Load terminal icon for -term service menu items
  const terminalIconPath = join(__dirname, '../assets/icons/terminal-icon.png');
  const terminalIcon = nativeImage.createFromPath(terminalIconPath);
  const resizedTerminalIcon = terminalIcon.resize({ width: 16, height: 16 });

  // Load pgadmin icon for -pgadmin service menu items
  const pgadminIconPath = join(__dirname, '../assets/icons/pgadmin-icon.png');
  const pgadminIcon = nativeImage.createFromPath(pgadminIconPath);
  const resizedPgadminIcon = pgadminIcon.resize({ width: 16, height: 16 });

  // Load hard drive icon for Backup / Restore menu
  const hardDriveIconPath = join(__dirname, '../assets/icons/hard-drive-icon.png');
  const hardDriveIcon = nativeImage.createFromPath(hardDriveIconPath);
  const resizedHardDriveIcon = hardDriveIcon.resize({ width: 16, height: 16 });

  // Load IgniteAI icon
  const igniteAiIconPath = join(__dirname, '../assets/icons/ignite-ai-icon.png');
  const igniteAiIcon = nativeImage.createFromPath(igniteAiIconPath);
  const resizedIgniteAiIcon = igniteAiIcon.resize({ width: 16, height: 16 });

  // Get inst_domain for Services menu
  const instDomain = await getInstDomain();
  const hasInstDomain = instDomain !== null;

  // Get running canvas containers for Services submenu
  const canvasContainers = await getRunningCanvasContainers();

  // Get FRPC status for instructure.cloud public links
  const frpcStatus = await checkFrpcConfigStatus();

  const template: MenuItemConstructorOptions[] = [
    {
      label: 'About Instructure Agent',
      click: () => {
        log.info('About menu item clicked');
        showAboutDialog();
      }
    },
    { type: 'separator' },
    {
      label: 'Canvas Setup',
      icon: resizedCanvasIcon,
      click: () => {
        log.info('Canvas Setup menu item clicked');
        showSetupWizardWindow();
      }
    },
    {
      label: 'Canvas Actions',
      icon: resizedCanvasActionsIcon,
      click: () => {
        log.info('Canvas Actions menu item clicked');
        showActionsWindow();
      }
    },
    { type: 'separator' },
    {
      label: 'Career Setup',
      icon: resizedCanvasIcon,
      click: () => {
        log.info('Career Setup menu item clicked');
        showCareerWizardWindow();
      }
    },
    { type: 'separator' },
    {
      label: 'Learner Hub Setup',
      icon: resizedCanvasIcon,
      click: () => {
        log.info('Learner Hub Setup menu item clicked');
        showLearnerHubWindow();
      }
    },
    { type: 'separator' },
    {
      label: 'Backup / Restore',
      icon: resizedHardDriveIcon,
      click: () => {
        log.info('Backup / Restore menu item clicked');
        showBackupRestoreWindow();
      }
    },
    {
      label: 'IgniteAI',
      icon: resizedIgniteAiIcon,
      click: () => {
        log.info('IgniteAI menu item clicked');
        showIgniteAiWindow();
      }
    },
    { type: 'separator' },
    {
      label: 'Services',
      submenu: [
        {
          label: 'Traefik Proxy',
          icon: resizedTraefikIcon,
          enabled: hasInstDomain,
          click: () => {
            if (instDomain) {
              const url = `http://dashboard.${instDomain}`;
              log.info(`Opening Traefik Proxy at ${url}`);
              shell.openExternal(url);
            }
          }
        },
        {
          label: 'Dozzle Logs',
          icon: resizedDozzleIcon,
          enabled: hasInstDomain,
          click: () => {
            if (instDomain) {
              const url = `http://logs.${instDomain}`;
              log.info(`Opening Dozzle Logs at ${url}`);
              shell.openExternal(url);
            }
          }
        },
        ...(canvasContainers.length > 0
          ? [
              { type: 'separator' as const },
              ...canvasContainers.map(containerName => ({
                label: containerName,
                icon: containerName.includes('-term') ? resizedTerminalIcon : containerName.includes('-pgadmin') ? resizedPgadminIcon : resizedCanvasIcon,
                enabled: hasInstDomain,
                click: () => {
                  if (instDomain) {
                    const url = `http://${containerName}.${instDomain}`;
                    log.info(`Opening Canvas instance at ${url}`);
                    shell.openExternal(url);
                  }
                }
              }))
            ]
          : []),
        ...(frpcStatus.isRunning && frpcStatus.frpcUsername && canvasContainers.length > 0
          ? [
              { type: 'separator' as const },
              ...canvasContainers.map(containerName => {
                const publicUrl = `https://${containerName}-${frpcStatus.frpcUsername}.instructure.cloud`;
                return {
                  label: `${containerName} (public)`,
                  icon: containerName.includes('-term') ? resizedTerminalIcon : containerName.includes('-pgadmin') ? resizedPgadminIcon : resizedCanvasIcon,
                  click: () => {
                    log.info(`Opening public Canvas site at ${publicUrl}`);
                    shell.openExternal(publicUrl);
                  }
                };
              })
            ]
          : [])
      ]
    },
    { type: 'separator' },
    {
      label: 'Instructure Agent Settings',
      accelerator: 'Cmd+,',
      click: () => {
        log.info('Settings menu item clicked');
        showSettingsWindow();
      }
    },
    {
      label: 'Check for Updates...',
      click: () => {
        log.info('Check for Updates menu item clicked');
        checkForUpdates(true); // Pass true to show dialogs for all results
      }
    },
    { type: 'separator' },
    {
      label: 'Quit',
      accelerator: 'Cmd+Q',
      click: () => {
        log.info('Quit menu item clicked');
        app.quit();
      }
    }
  ];

  return Menu.buildFromTemplate(template);
}
