import { Tray, nativeImage } from 'electron';
import { join } from 'path';
import log from 'electron-log';
import { createMenu } from './menu';

let tray: Tray | null = null;
let onOpenCallback: (() => void) | null = null;

export async function createTray(onOpen: () => void): Promise<Tray> {
  onOpenCallback = onOpen;
  if (tray) {
    log.warn('Tray already exists');
    return tray;
  }

  // Load tray icon
  // In production: __dirname is dist/main, icon is at dist/assets/icons/tray-icon.png
  // In development: same structure
  const iconPath = join(__dirname, '../assets/icons/tray-icon.png');
  log.info(`Loading tray icon from: ${iconPath}`);

  const icon = nativeImage.createFromPath(iconPath);

  if (icon.isEmpty()) {
    log.error(`Failed to load tray icon from ${iconPath}`);
  }

  // Create tray - nativeImage automatically handles @2x for Retina displays
  // Set as template image for automatic light/dark mode adaptation on macOS
  tray = new Tray(icon);
  tray.setImage(icon);

  tray.setToolTip('Instructure Agent');

  // Create and set menu
  const menu = await createMenu(onOpen);
  tray.setContextMenu(menu);

  // Handle tray click - update menu before showing to reflect current state
  tray.on('click', async () => {
    log.info('Tray icon clicked - updating menu before display');
    if (tray && onOpenCallback) {
      const updatedMenu = await createMenu(onOpenCallback);
      tray.setContextMenu(updatedMenu);
    }
    tray?.popUpContextMenu();
  });

  // Handle right-click on tray - update menu before showing
  tray.on('right-click', async () => {
    log.info('Tray right-clicked - updating menu before display');
    if (tray && onOpenCallback) {
      const updatedMenu = await createMenu(onOpenCallback);
      tray.setContextMenu(updatedMenu);
    }
  });

  log.info('Tray created successfully');
  return tray;
}

export function destroyTray(): void {
  if (tray) {
    tray.destroy();
    tray = null;
    log.info('Tray destroyed');
  }
}

/**
 * Update tray icon based on status
 * @param allStepsPassing - true if all onboarding steps are passing
 */
export function updateTrayIcon(allStepsPassing: boolean): void {
  if (!tray) {
    log.warn('Cannot update tray icon - tray does not exist');
    return;
  }

  const iconName = allStepsPassing ? 'tray-green-icon.png' : 'tray-orange-icon.png';
  const iconPath = join(__dirname, '../assets/icons', iconName);

  log.info(`Updating tray icon to: ${iconName} (allStepsPassing: ${allStepsPassing})`);

  const icon = nativeImage.createFromPath(iconPath);

  if (icon.isEmpty()) {
    log.error(`Failed to load tray icon from ${iconPath}`);
    return;
  }

  tray.setImage(icon);
  log.info('Tray icon updated successfully');
}

