import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:sigap/src/cores/services/biometric_service.dart';
import 'package:sigap/src/features/auth/data/repositories/authentication_repository.dart';
import 'package:sigap/src/features/personalization/presentasion/controllers/settings/base_settings_controller.dart';
import 'package:sigap/src/utils/popups/loaders.dart';

class SecurityController extends BaseSettingsController {
  final _logger = Logger();
  final _biometricService = Get.find<BiometricService>();
  final _authRepo = Get.find<AuthenticationRepository>();

  // Security settings
  final RxBool requireBiometric = false.obs;
  final RxBool enable2FA = false.obs;
  final RxBool sendEmailAlerts = true.obs;
  final RxBool sendPushNotification = false.obs;

  // Passcode information
  final RxBool hasPasscode = false.obs;
  final RxString passcodeLastChanged = ''.obs;

  // 2FA backup codes
  final RxList<String> backupCodes = <String>[].obs;

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

  // Toggle biometric security setting
  Future<bool> toggleBiometricAuthentication(bool enable) async {
    try {
      setLoading(true);

      if (enable) {
        // Check if biometrics is available
        if (!_biometricService.isBiometricAvailable.value) {
          setError('Biometric authentication is not available on this device');
          TLoaders.warningSnackBar(
            title: 'Not Available',
            message: 'Biometric authentication is not available on your device',
          );
          return false;
        }

        // Try to authenticate before enabling
        bool authenticated = await _biometricService.authenticate(
          reason: 'Authenticate to enable biometric login',
        );

        if (!authenticated) {
          setError('Biometric authentication failed');
          return false;
        }

        // Enable biometric login
        await _biometricService.enableBiometricLogin();
        requireBiometric.value = true;
        TLoaders.successSnackBar(
          title: 'Enabled',
          message: 'Biometric authentication has been enabled',
        );
      } else {
        // Disable biometric login
        await _biometricService.disableBiometricLogin();
        requireBiometric.value = false;
        TLoaders.successSnackBar(
          title: 'Disabled',
          message: 'Biometric authentication has been disabled',
        );
      }

      return true;
    } catch (e) {
      _logger.e('Error toggling biometric authentication: $e');
      setError('Failed to change biometric settings: ${e.toString()}');
      TLoaders.errorSnackBar(
        title: 'Error',
        message: 'Failed to change biometric settings',
      );
      return false;
    } finally {
      setLoading(false);
    }
  }

  // Toggle other security settings
  void toggleSecuritySetting(String setting, bool value) {
    switch (setting) {
      case 'require_biometric':
        requireBiometric.value = value;
        break;
      case 'enable_2fa':
        enable2FA.value = value;
        break;
      case 'send_email_alerts':
        sendEmailAlerts.value = value;
        break;
      case 'send_push_notification':
        sendPushNotification.value = value;
        break;
    }

    saveSettings();
  }

  // Generate new backup codes (normally would call an API)
  Future<bool> generateBackupCodes() async {
    try {
      setLoading(true);

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

      // Generate random codes for demo purposes
      final List<String> codes = List.generate(
        8,
        (_) => List.generate(
          6,
          (_) =>
              (0 + (9 - 0) * (DateTime.now().microsecondsSinceEpoch % 10))
                  .toString(),
        ).join(''),
      );

      backupCodes.value = codes;
      return true;
    } catch (e) {
      setError('Failed to generate backup codes: ${e.toString()}');
      return false;
    } finally {
      setLoading(false);
    }
  }

  // Change passcode
  Future<bool> changePasscode(
    String currentPasscode,
    String newPasscode,
  ) async {
    try {
      setLoading(true);

      // TODO: Implement passcode change logic
      // Normally would validate the current passcode and save the new one

      hasPasscode.value = true;
      passcodeLastChanged.value = DateTime.now().toIso8601String();
      await saveSettings();

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

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

      // TODO: Save security settings to persistent storage
      final prefs = Get.find<dynamic>(); // Replace with your storage solution
      // await prefs.setBool('require_biometric', requireBiometric.value);
      // await prefs.setBool('enable_2fa', enable2FA.value);
      // await prefs.setBool('send_email_alerts', sendEmailAlerts.value);
      // await prefs.setBool('send_push_notification', sendPushNotification.value);
      // await prefs.setBool('has_passcode', hasPasscode.value);
      // await prefs.setString('passcode_last_changed', passcodeLastChanged.value);
      // await prefs.setStringList('backup_codes', backupCodes);

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

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

      // Load biometric setting from actual service
      requireBiometric.value =
          await _biometricService.isBiometricLoginEnabled();

      // TODO: Load security settings from persistent storage
      final prefs = Get.find<dynamic>(); // Replace with your storage solution
      // requireBiometric.value = prefs.getBool('require_biometric') ?? true;
      // enable2FA.value = prefs.getBool('enable_2fa') ?? false;
      // sendEmailAlerts.value = prefs.getBool('send_email_alerts') ?? true;
      // sendPushNotification.value = prefs.getBool('send_push_notification') ?? false;
      // hasPasscode.value = prefs.getBool('has_passcode') ?? false;
      // passcodeLastChanged.value = prefs.getString('passcode_last_changed') ?? '';
      // backupCodes.value = prefs.getStringList('backup_codes') ?? [];
    } catch (e) {
      _logger.e('Failed to load security settings: $e');
      setError('Failed to load security settings: ${e.toString()}');
    } finally {
      setLoading(false);
    }
  }
}
