import { ipcMain, BrowserWindow } from 'electron';
import log from 'electron-log';
import { settingsStore, LearnerHubSetupState } from '../store';
import { getLearnerHubSteps } from '../learner-hub/steps';
import { checkStepsAndUpdateTrayIcon } from '../index';
import type { CacheManager } from '../services/cache-manager';

export type LearnerHubCacheKey = 'learnerHubSteps' | 'learnerHubState';

export function registerLearnerHubHandlers(
  cache: CacheManager<LearnerHubCacheKey, any>
): void {
  // State management
  ipcMain.handle('learner-hub:get-state', async () => {
    try {
      const cached = cache.get('learnerHubState');
      if (cached) return cached;
      const state = settingsStore.get('learnerHubSetup');
      cache.set('learnerHubState', state);
      return state;
    } catch (error) {
      log.error('Error getting learner hub state:', error);
      throw error;
    }
  });

  ipcMain.handle('learner-hub:set-state', async (_event, state: LearnerHubSetupState) => {
    try {
      settingsStore.set('learnerHubSetup', state);
      cache.invalidate('learnerHubState');
    } catch (error) {
      log.error('Error setting learner hub state:', error);
      throw error;
    }
  });

  // Steps
  ipcMain.handle('learner-hub:get-steps', async () => {
    try {
      const cached = cache.get('learnerHubSteps');
      if (cached) return cached;

      const steps = getLearnerHubSteps().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('learnerHubSteps', steps);
      return steps;
    } catch (error) {
      log.error('Error getting learner hub steps:', error);
      throw error;
    }
  });

  ipcMain.handle('learner-hub:validate-step', async (_event, stepId: string) => {
    try {
      const steps = getLearnerHubSteps();
      const step = steps.find(s => s.id === stepId);
      if (!step) throw new Error(`Learner Hub step not found: ${stepId}`);
      const result = await step.validate();
      log.info(`Learner Hub step validation for ${stepId}:`, result);
      return result;
    } catch (error) {
      log.error('Error validating learner hub step:', error);
      throw error;
    }
  });

  // Repository operations
  ipcMain.handle('learner-hub:clone-repository', async (event, baseDirectory: string) => {
    try {
      const window = BrowserWindow.fromWebContents(event.sender);
      if (!window) throw new Error('Could not find window');
      const { cloneLearnerHubRepository } = require('../services/learner-hub-manager');
      return await cloneLearnerHubRepository(window, baseDirectory);
    } catch (error) {
      log.error('Error cloning learner-hub repository:', error);
      throw error;
    }
  });

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

  ipcMain.handle('learner-hub:reset-repository', async (event, baseDirectory: string) => {
    try {
      const window = BrowserWindow.fromWebContents(event.sender);
      if (!window) throw new Error('Could not find window');
      const { resetLearnerHubRepository } = require('../services/learner-hub-manager');
      return await resetLearnerHubRepository(window, baseDirectory);
    } catch (error) {
      log.error('Error resetting learner-hub repository:', error);
      throw error;
    }
  });

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

  // Folder selection
  ipcMain.handle('learner-hub: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 learner-hub folder:', error);
      throw error;
    }
  });

  ipcMain.handle('learner-hub:save-folder', async (_event, folder: string) => {
    try {
      log.info('Saving learner-hub clone folder:', folder);
      const state = settingsStore.get('learnerHubSetup');

      const existingStepData = state.stepStatus['learner-hub-git-clone'] || {};
      const existingData = (existingStepData as any).data || {};

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

      settingsStore.set('learnerHubSetup', state);
      cache.invalidate('learnerHubState');

      const { createLearnerHubConfig } = require('../services/learner-hub-manager');
      await createLearnerHubConfig(folder);
    } catch (error) {
      log.error('Error saving learner-hub clone folder:', error);
      throw error;
    }
  });

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

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

  log.info('Learner Hub IPC handlers registered');
}
