import Store from 'electron-store';
import { Subject } from 'rxjs';
import log from 'electron-log';

export interface SetupWizardState {
  completed: boolean;
  lastShownVersion: string;
  stepStatus: {
    [stepId: string]: {
      completed: boolean;
      lastChecked: number;
      data?: Record<string, any>;
    };
  };
  dismissedAt?: number;
}

export interface CareerSetupState {
  completed: boolean;
  lastShownVersion: string;
  stepStatus: {
    [stepId: string]: {
      completed: boolean;
      lastChecked: number;
      data?: Record<string, any>;
    };
  };
  dismissedAt?: number;
  // Career-specific data
  baseCodeDirectory?: string;
  canvasHorizonPath?: string;
  journeyPath?: string;
}

export interface LearnerHubSetupState {
  completed: boolean;
  lastShownVersion: string;
  stepStatus: {
    [stepId: string]: {
      completed: boolean;
      lastChecked: number;
      data?: Record<string, any>;
    };
  };
  dismissedAt?: number;
  // Learner Hub-specific data
  baseDirectory?: string;
  learnerHubPath?: string;
}

export interface Settings {
  openShortcut: string;
  autoUpdate: boolean;
  githubToken: string;
  theme: 'light' | 'dark' | 'system';
  onboarding: SetupWizardState;
  careerSetup: CareerSetupState;
  learnerHubSetup: LearnerHubSetupState;
  multiDeploy: boolean;
}

const defaultSettings: Settings = {
  openShortcut: 'Alt+Space',
  autoUpdate: true,
  githubToken: '',
  theme: 'system',
  onboarding: {
    completed: false,
    lastShownVersion: '1.0.0',
    stepStatus: {},
    dismissedAt: undefined
  },
  careerSetup: {
    completed: false,
    lastShownVersion: '0.0.0',
    stepStatus: {},
    dismissedAt: undefined
  },
  learnerHubSetup: {
    completed: false,
    lastShownVersion: '0.0.0',
    stepStatus: {},
    dismissedAt: undefined
  },
  multiDeploy: true
};

class SettingsStore {
  private store: Store<Settings>;
  public settingsChanged$ = new Subject<{ key: keyof Settings; value: any }>();

  constructor() {
    this.store = new Store<Settings>({
      defaults: defaultSettings,
      name: 'settings'
    });

    log.info('Settings store initialized');
  }

  get<K extends keyof Settings>(key: K): Settings[K] {
    return this.store.get(key);
  }

  set<K extends keyof Settings>(key: K, value: Settings[K]): void {
    this.store.set(key, value);
    this.settingsChanged$.next({ key, value });
    log.info(`Setting updated: ${key} = ${value}`);
  }

  getAll(): Settings {
    return this.store.store;
  }

  reset(): void {
    this.store.clear();
    log.info('Settings reset to defaults');
  }
}

export const settingsStore = new SettingsStore();
