import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../constant/box_name.dart';
import '../../main.dart';
import '../themes/themes.dart';

class LocaleController extends GetxController {
  Locale? language;
  String countryCode = '';

  ThemeMode themeMode = ThemeMode.system;

  void changeLang(String langcode) {
    Locale newLocale;
    ThemeData newTheme;
    bool isArabic = langcode.startsWith('ar');

    if (isArabic) {
      newLocale = const Locale("ar");
      newTheme = Get.isDarkMode ? darkThemeArabic : lightThemeArabic;
    } else {
      newLocale = const Locale("en");
      newTheme = Get.isDarkMode ? darkThemeEnglish : lightThemeEnglish;
    }

    box.write(BoxName.lang, langcode);
    language = newLocale;
    Get.changeTheme(newTheme);
    Get.updateLocale(newLocale);
    update();
  }

  void changeThemeMode(ThemeMode mode) {
    themeMode = mode;
    Get.changeThemeMode(mode);

    // Explicitly update ThemeData to ensure immediate font and color changes
    bool goDark = mode == ThemeMode.dark ||
        (mode == ThemeMode.system && Get.isPlatformDarkMode);
    bool isArabic = (language?.languageCode ?? 'en').startsWith('ar');

    ThemeData newTheme;
    if (isArabic) {
      newTheme = goDark ? darkThemeArabic : lightThemeArabic;
    } else {
      newTheme = goDark ? darkThemeEnglish : lightThemeEnglish;
    }
    Get.changeTheme(newTheme);

    box.write(BoxName.themeMode, mode.toString());
    update();
  }

  @override
  void onInit() {
    String? storedLang = box.read(BoxName.lang);
    if (storedLang == null) {
      // Use device language if no language is stored
      storedLang = Get.deviceLocale!.languageCode;
      box.write(BoxName.lang, storedLang);
    }

    String? storedTheme = box.read(BoxName.themeMode);
    if (storedTheme != null) {
      if (storedTheme == ThemeMode.light.toString()) {
        themeMode = ThemeMode.light;
      } else if (storedTheme == ThemeMode.dark.toString()) {
        themeMode = ThemeMode.dark;
      } else {
        themeMode = ThemeMode.system;
      }
    }

    changeLang(storedLang);
    super.onInit();
  }
}
