import 'package:flutter/material.dart';

import '../../../../core/logging/app_logger.dart';
import '../../data/settings_local_datasource.dart';
import '../../domain/enums/app_mode.dart';

class SettingsViewModel extends ChangeNotifier {
  final SettingsLocalDataSource dataSource;
  final AppLogger logger;

  SettingsViewModel({
    required this.dataSource,
    required this.logger,
  }) {
    _loadSettings();
  }

  Locale? _locale;
  ThemeMode _themeMode = ThemeMode.system;
  AppMode? _appMode;
  bool _setupCompleted = false;
  bool _onboardingShown = false;

  Locale? get locale => _locale;
  ThemeMode get themeMode => _themeMode;
  AppMode? get appMode => _appMode;
  bool get setupCompleted => _setupCompleted;
  bool get onboardingShown => _onboardingShown;
  bool get isLocalMode => _appMode == AppMode.local;
  bool get isOnlineMode => _appMode == AppMode.online;

  static const supportedLocales = [
    Locale('en'),
    Locale('de'),
  ];

  void _loadSettings() {
    _locale = dataSource.getLocale() ?? const Locale('en');
    _themeMode = dataSource.getThemeMode();
    _appMode = dataSource.getAppMode();
    _setupCompleted = dataSource.isSetupCompleted();
    _onboardingShown = dataSource.isOnboardingShown();
    logger.info('Settings loaded: locale=$_locale, themeMode=$_themeMode, appMode=$_appMode, setupCompleted=$_setupCompleted, onboardingShown=$_onboardingShown');
  }

  Future<void> setLocale(Locale locale) async {
    _locale = locale;
    await dataSource.setLocale(locale);
    logger.info('Locale changed to: ${locale.languageCode}');
    notifyListeners();
  }

  Future<void> setThemeMode(ThemeMode mode) async {
    _themeMode = mode;
    await dataSource.setThemeMode(mode);
    logger.info('Theme mode changed to: $mode');
    notifyListeners();
  }

  Future<void> setAppMode(AppMode mode) async {
    _appMode = mode;
    await dataSource.setAppMode(mode);
    logger.info('App mode changed to: $mode');
    notifyListeners();
  }

  Future<void> setSetupCompleted(bool completed) async {
    _setupCompleted = completed;
    await dataSource.setSetupCompleted(completed);
    logger.info('Setup completed: $completed');
    notifyListeners();
  }

  Future<void> setOnboardingShown(bool shown) async {
    _onboardingShown = shown;
    await dataSource.setOnboardingShown(shown);
    logger.info('Onboarding shown: $shown');
    notifyListeners();
  }

  String getLanguageName(Locale locale) {
    switch (locale.languageCode) {
      case 'en':
        return 'English';
      case 'de':
        return 'Deutsch';
      default:
        return locale.languageCode.toUpperCase();
    }
  }
}
