import { ipcMain, BrowserWindow } from 'electron';
import log from 'electron-log';
import { settingsStore, CareerSetupState } from '../store';
import { getCareerWizardSteps } from '../career-wizard/steps';
import { checkStepsAndUpdateTrayIcon } from '../index';
import type { CacheManager } from '../services/cache-manager';

export type CareerWizardCacheKey = 'careerSteps' | 'careerState';

/**
 * Register career wizard IPC handlers
 */
export function registerCareerWizardHandlers(
  cache: CacheManager<CareerWizardCacheKey, any>
): void {
  // Career state management
  ipcMain.handle('career-wizard:get-state', async () => {
    try {
      const cached = cache.get('careerState');
      if (cached) {
        log.info('Returning cached career wizard state');
        return cached;
      }

      const state = settingsStore.get('careerSetup');
      cache.set('careerState', state);
      return state;
    } catch (error) {
      log.error('Error getting career wizard state:', error);
      throw error;
    }
  });

  ipcMain.handle('career-wizard:set-state', async (_event, state: CareerSetupState) => {
    try {
      settingsStore.set('careerSetup', state);
      cache.invalidate('careerState');
      log.info('Career wizard state updated');
    } catch (error) {
      log.error('Error setting career wizard state:', error);
      throw error;
    }
  });

  // Career steps
  ipcMain.handle('career-wizard:get-steps', async () => {
    try {
      const cached = cache.get('careerSteps');
      if (cached) {
        log.info('Returning cached career wizard steps');
        return cached;
      }

      const steps = getCareerWizardSteps().map(step => ({
        id: step.id,
        title: step.title,
        description: step.description,
        componentName: step.componentName,
        order: step.order,
        required: step.required,
        icon: step.icon
      }));

      cache.set('careerSteps', steps);
      return steps;
    } catch (error) {
      log.error('Error getting career wizard steps:', error);
      throw error;
    }
  });

  ipcMain.handle('career-wizard:validate-step', async (_event, stepId: string) => {
    try {
      const steps = getCareerWizardSteps();
      const step = steps.find(s => s.id === stepId);

      if (!step) {
        throw new Error(`Career wizard step not found: ${stepId}`);
      }

      const result = await step.validate();
      log.info(`Career wizard step validation for ${stepId}:`, result);
      return result;
    } catch (error) {
      log.error('Error validating career wizard step:', error);
      throw error;
    }
  });

  // Career-specific operations
  ipcMain.handle('career-wizard:clone-repositories', async (event, baseDirectory: string) => {
    try {
      const window = BrowserWindow.fromWebContents(event.sender);
      if (!window) {
        throw new Error('Could not find window');
      }

      // Import career manager service
      const { cloneCareerRepositories } = require('../services/career-manager');
      return await cloneCareerRepositories(window, baseDirectory);
    } catch (error) {
      log.error('Error cloning career repositories:', error);
      throw error;
    }
  });

  ipcMain.handle('career-wizard:get-repositories-status', async (_event, baseDirectory?: string) => {
    try {
      const { checkCareerRepositoriesStatus } = require('../services/career-manager');
      return await checkCareerRepositoriesStatus(baseDirectory);
    } catch (error) {
      log.error('Error getting career repositories status:', error);
      throw error;
    }
  });

  ipcMain.handle('career-wizard:reset-repositories', async (event, baseDirectory: string) => {
    try {
      const window = BrowserWindow.fromWebContents(event.sender);
      if (!window) {
        throw new Error('Could not find window');
      }

      const { resetCareerRepositories } = require('../services/career-manager');
      return await resetCareerRepositories(window, baseDirectory);
    } catch (error) {
      log.error('Error resetting career repositories:', error);
      throw error;
    }
  });

  ipcMain.handle('career-wizard:get-config', async () => {
    try {
      const { checkCareerConfig } = require('../services/career-manager');
      return await checkCareerConfig();
    } catch (error) {
      log.error('Error getting career config:', error);
      throw error;
    }
  });

  ipcMain.handle('career-wizard:create-config', async (_event, config: any) => {
    try {
      // Import career manager service
      const { createCareerConfig } = require('../services/career-manager');
      await createCareerConfig(config.baseDirectory);
      return {
        success: true,
        message: 'Configuration file created successfully'
      };
    } catch (error: any) {
      log.error('Error creating career config:', error);
      return {
        success: false,
        message: error.message
      };
    }
  });

  // Folder selection for career repositories
  ipcMain.handle('career-wizard:select-folder', async (event) => {
    try {
      const { selectCloneFolder } = require('../services/git-clone-manager');
      const window = BrowserWindow.fromWebContents(event.sender);
      return await selectCloneFolder(window);
    } catch (error) {
      log.error('Error selecting career repository folder:', error);
      throw error;
    }
  });

  ipcMain.handle('career-wizard:save-folder', async (_event, folder: string) => {
    try {
      log.info('Saving career clone folder:', folder);
      const careerState = settingsStore.get('careerSetup');

      // Preserve existing data if it exists
      const existingStepData = careerState.stepStatus['career-git-clone'] || {};
      const existingData = existingStepData.data || {};

      careerState.stepStatus['career-git-clone'] = {
        ...existingStepData,
        completed: false,
        lastChecked: Date.now(),
        data: {
          ...existingData,
          baseDirectory: folder
        }
      };

      settingsStore.set('careerSetup', careerState);
      cache.invalidate('careerState');

      // Also update the career.yml configuration file
      const { createCareerConfig } = require('../services/career-manager');
      await createCareerConfig(folder);
      log.info('Updated career.yml configuration file');

      return;
    } catch (error) {
      log.error('Error saving career clone folder:', error);
      throw error;
    }
  });

  // Helper to open Canvas Setup window
  ipcMain.handle('career-wizard:open-canvas-setup', async () => {
    try {
      const { showSetupWizardWindow } = require('../setup-wizard-window');
      showSetupWizardWindow();
    } catch (error) {
      log.error('Error opening Canvas Setup window:', error);
      throw error;
    }
  });

  // Update tray icon
  ipcMain.handle('career-wizard:update-tray-icon', async () => {
    try {
      await checkStepsAndUpdateTrayIcon();
    } catch (error) {
      log.error('Error updating tray icon:', error);
      throw error;
    }
  });

  log.info('Career wizard IPC handlers registered');
}
