import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:sigap/src/features/auth/data/repositories/authentication_repository.dart';
import 'package:sigap/src/features/personalization/data/models/models/profile_model.dart';
import 'package:sigap/src/features/personalization/data/models/models/users_model.dart';
import 'package:sigap/src/features/personalization/presentasion/controllers/settings/base_settings_controller.dart';
import 'package:sigap/src/features/personalization/presentasion/controllers/settings/display_mode_controller.dart';
import 'package:sigap/src/features/personalization/presentasion/controllers/settings/email_controller.dart';
import 'package:sigap/src/features/personalization/presentasion/controllers/settings/language_controller.dart';
import 'package:sigap/src/features/personalization/presentasion/controllers/settings/notifications_controller.dart';
import 'package:sigap/src/features/personalization/presentasion/controllers/settings/privacy_controller.dart';
import 'package:sigap/src/features/personalization/presentasion/controllers/settings/security_controller.dart';
import 'package:sigap/src/features/personalization/presentasion/controllers/settings/text_size_controller.dart';
import 'package:sigap/src/shared/widgets/loaders/custom_circular_loader.dart';
import 'package:sigap/src/utils/popups/dialogs.dart';
import 'package:sigap/src/utils/popups/loaders.dart';

class SettingsController extends BaseSettingsController {
  // Singleton instance
  static SettingsController get instance => Get.find<SettingsController>();
  
  // User info
  final Rx<UserModel?> currentUser = Rx<UserModel?>(null);
  final Rx<ProfileModel?> userProfile = Rx<ProfileModel?>(null);

  // Get auth repository for sign out functionality
  final AuthenticationRepository _authRepo =
      Get.find<AuthenticationRepository>();

  // Current tab index
  final RxInt selectedTabIndex = 0.obs;

  // References to sub-controllers
  late final DisplayModeController displayModeController;
  late final LanguageController languageController;
  late final NotificationsController notificationsController;
  late final PrivacyController privacyController;
  late final SecurityController securityController;
  late final EmailController emailController;
  late final TextSizeController textSizeController;

  // Track sign out loading state
  final RxBool isSigningOut = false.obs;

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

  void initializeControllers() {
    // Initialize all sub-controllers
    displayModeController = Get.find<DisplayModeController>();
    languageController = Get.find<LanguageController>();
    notificationsController = Get.find<NotificationsController>();
    privacyController = Get.find<PrivacyController>();
    securityController = Get.find<SecurityController>();
    emailController = Get.find<EmailController>();
    textSizeController = Get.find<TextSizeController>();
  }

  void changeTab(int index) {
    selectedTabIndex.value = index;
  }

  // Log out user
  Future<bool> logout() async {
    try {
      setLoading(true);

      // TODO: Implement logout logic
      // Clear user session, tokens, etc.

      // Simulate API call
      await Future.delayed(const Duration(seconds: 1));

      // Clear user data
      currentUser.value = null;
      userProfile.value = null;

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

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

      // Save all sub-controller settings
      await displayModeController.saveSettings();
      await languageController.saveSettings();
      await notificationsController.saveSettings();
      await privacyController.saveSettings();
      await securityController.saveSettings();
      await emailController.saveSettings();
      await textSizeController.saveSettings();

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

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

      // TODO: Load user data
      // Normally would fetch from an API or local storage

      // For demo purposes, create a dummy user
      // currentUser.value = UserModel(/* ... */);
      // userProfile.value = ProfileModel(/* ... */);
    } catch (e) {
      setError('Failed to load user settings: ${e.toString()}');
    } finally {
      setLoading(false);
    }
  }

  // Handle sign out with confirmation
  void handleSignOut(BuildContext context) {
    TDialogs.confirmDialog(
      context: context,
      title: 'Sign Out',
      message: 'Are you sure you want to sign out?',
      onConfirm: () async {
        try {
          isSigningOut.value = true;

          TLoader.fullScreenLoader(text: 'Signing out, please wait...');

          await _authRepo.signOut();

          isSigningOut.value = false;
        } catch (e) {
          isSigningOut.value = false;
          // Show error snackbar if sign out fails
          TLoaders.errorSnackBar(
            title: 'Sign Out Failed',
            message: 'Failed to sign out. please try again later.',
          );
        }
      },
    );
  }
}
