import 'dart:ui';
import 'package:shared_preferences/shared_preferences.dart';

class LocaleManager {
  static const String _localeKey = 'selected_locale';
  static const List<Locale> supportedLocales = [
    Locale('en', ''), // English
    Locale('de', ''), // German
    Locale('hu', ''), // Hungarian
  ];

  static Locale _currentLocale = const Locale('en', '');
  static void Function()? _onLocaleChanged;

  static Locale get currentLocale => _currentLocale;

  /// Set callback for when locale changes
  static void setLocaleChangeCallback(void Function() callback) {
    _onLocaleChanged = callback;
  }

  /// Initialize the locale manager and load saved locale
  static Future<void> init() async {
    final prefs = await SharedPreferences.getInstance();
    final savedLocaleCode = prefs.getString(_localeKey);
    
    if (savedLocaleCode != null) {
      // Find the saved locale in supported locales
      final savedLocale = supportedLocales.firstWhere(
        (locale) => locale.languageCode == savedLocaleCode,
        orElse: () => _getSystemLocale(),
      );
      _currentLocale = savedLocale;
    } else {
      // Use system locale if available, otherwise default to English
      _currentLocale = _getSystemLocale();
    }
  }

  /// Get the system locale if supported, otherwise return English
  static Locale _getSystemLocale() {
    final systemLocale = PlatformDispatcher.instance.locale;
    
    // Check if system locale is supported
    for (final supportedLocale in supportedLocales) {
      if (supportedLocale.languageCode == systemLocale.languageCode) {
        return supportedLocale;
      }
    }
    
    // Default to English if system locale is not supported
    return const Locale('en', '');
  }

  /// Change the current locale and save it to preferences
  static Future<void> setLocale(Locale locale) async {
    if (supportedLocales.contains(locale)) {
      _currentLocale = locale;
      
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString(_localeKey, locale.languageCode);
      
      // Trigger app refresh to apply new locale
      _onLocaleChanged?.call();
    }
  }

  /// Get locale display name
  static String getLocaleDisplayName(Locale locale) {
    switch (locale.languageCode) {
      case 'en':
        return 'English';
      case 'de':
        return 'Deutsch';
      case 'hu':
        return 'Magyar';
      default:
        return locale.languageCode;
    }
  }

  /// Check if a locale is supported
  static bool isLocaleSupported(Locale locale) {
    return supportedLocales.any(
      (supportedLocale) => supportedLocale.languageCode == locale.languageCode,
    );
  }
}