import 'dart:ui';

import 'package:get/get.dart';
import 'package:sigap/src/features/personalization/presentasion/controllers/settings/base_settings_controller.dart';

class LanguageController extends BaseSettingsController {
  // Available languages with their locale codes
  final List<Map<String, String>> availableLanguages = [
    {'name': 'English (US)', 'code': 'en_US'},
    {'name': 'Bahasa Indonesia', 'code': 'id_ID'},
    {'name': 'Español', 'code': 'es_ES'},
    {'name': 'Français', 'code': 'fr_FR'},
    {'name': '日本語', 'code': 'ja_JP'},
    {'name': '한국어', 'code': 'ko_KR'},
  ];

  // Current selected language
  final RxString selectedLanguage = 'English (US)'.obs;

  @override
  void onInit() {
    super.onInit();
    loadSettings();
  }

  // Change language
  void changeLanguage(String language) {
    final languageItem = availableLanguages.firstWhere(
      (lang) => lang['name'] == language,
      orElse: () => {'name': 'English (US)', 'code': 'en_US'},
    );

    selectedLanguage.value = language;
    final String localeCode = languageItem['code'] ?? 'en_US';
    final List<String> localeParts = localeCode.split('_');

    // Apply the language change
    Get.updateLocale(
      Locale(localeParts[0], localeParts.length > 1 ? localeParts[1] : ''),
    );
    saveSettings();
  }

  @override
  Future<bool> saveSettings() async {
    try {
      setLoading(true);

      // TODO: Save the language setting to persistent storage
      final prefs = Get.find<dynamic>(); // Replace with your storage solution
      // await prefs.setString('selected_language', selectedLanguage.value);

      return true;
    } catch (e) {
      setError('Failed to save language settings: ${e.toString()}');
      return false;
    } finally {
      setLoading(false);
    }
  }

  @override
  Future<void> loadSettings() async {
    try {
      setLoading(true);

      // TODO: Load the language setting from persistent storage
      final prefs = Get.find<dynamic>(); // Replace with your storage solution
      // final savedLanguage = await prefs.getString('selected_language') ?? 'English (US)';
      // selectedLanguage.value = savedLanguage;

      // Apply the loaded language
      if (selectedLanguage.value != 'English (US)') {
        changeLanguage(selectedLanguage.value);
      }
    } catch (e) {
      setError('Failed to load language settings: ${e.toString()}');
    } finally {
      setLoading(false);
    }
  }
}
