import 'package:get/get.dart';
import 'package:local_auth/local_auth.dart';
import '../../../core/storage/secure_storage.dart';
import '../../../app/routes/app_pages.dart';
import '../../../core/utils/logger.dart';
import '../../../core/utils/app_snackbar.dart';

class BiometricController extends GetxController {
  final LocalAuthentication auth = LocalAuthentication();
  final SecureStorage _storage = SecureStorage();
  
  var isBiometricAvailable = false.obs;
  var isAuthenticating = false.obs;

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

  Future<void> checkBiometrics() async {
    try {
      final canCheck = await auth.canCheckBiometrics;
      final isSupported = await auth.isDeviceSupported();
      isBiometricAvailable.value = canCheck || isSupported;
      AppLogger.print('Biometrics available: ${isBiometricAvailable.value}');
    } catch (e, stackTrace) {
      isBiometricAvailable.value = false;
      AppLogger.error('Failed to check biometrics support', e, stackTrace);
    }
  }

  Future<void> authenticateAndGoToDashboard() async {
    // Ensure we have checked biometric status first
    await checkBiometrics();
    
    if (!isBiometricAvailable.value) {
      AppLogger.print('Biometrics not available, going directly to dashboard.');
      Get.offAllNamed(AppRoutes.DASHBOARD);
      return;
    }

    try {
      isAuthenticating.value = true;
      bool authenticated = await auth.authenticate(
        localizedReason: 'الرجاء التحقق من هويتك للوصول إلى مُصادَق',
        options: const AuthenticationOptions(
          stickyAuth: true,
          biometricOnly: false, // Allows PIN/Pattern fallback
        ),
      );

      if (authenticated) {
        AppLogger.print('Biometric authentication successful!');
        Get.offAllNamed(AppRoutes.DASHBOARD);
      } else {
        AppLogger.print('Biometric authentication cancelled or failed.');
        AppSnackbar.showWarning('فشل التحقق', 'لم نتمكن من التحقق من هويتك أو قمت بإلغاء العملية');
      }
    } catch (e, stackTrace) {
      AppLogger.error('Error during biometric auth', e, stackTrace);
      AppSnackbar.showError('خطأ', 'حدث خطأ غير متوقع أثناء قراءة البصمة: $e');
    } finally {
      isAuthenticating.value = false;
    }
  }

  void skipBiometricSetup() {
    AppLogger.print('Skipped biometric setup.');
    Get.offAllNamed(AppRoutes.DASHBOARD);
  }
}
