import 'package:sefer_driver/constant/box_name.dart';
import 'package:sefer_driver/controller/auth/captin/login_captin_controller.dart';
import 'package:sefer_driver/controller/functions/crud.dart';
import 'package:sefer_driver/main.dart';
import 'package:sefer_driver/views/auth/captin/cards/sms_signup.dart';
import 'package:sefer_driver/views/home/on_boarding_page.dart';
import 'package:sefer_driver/views/widgets/error_snakbar.dart';
import 'package:get/get.dart';
import 'package:google_sign_in/google_sign_in.dart';

import '../../views/auth/captin/ai_page.dart';
import '../functions/add_error.dart';
import '../functions/encrypt_decrypt.dart';

class GoogleSignInHelper {
  static final GoogleSignIn _googleSignIn = GoogleSignIn.instance;

  // متغير ثابت لحفظ حالة المستخدم محلياً كبديل لخاصية currentUser المحذوفة
  static GoogleSignInAccount? _cachedUser;

  static Future<GoogleSignInAccount?> signIn() async {
    try {
      final GoogleSignInAccount? googleUser =
          await _googleSignIn.authenticate();

      if (googleUser != null) {
        _cachedUser = googleUser; // حفظ الجلسة في الكاش المحلي
        await _handleSignUp(googleUser);

        if (box.read(BoxName.countryCode) == 'Egypt') {
          Get.to(() => SmsSignupEgypt());
        } else if (box.read(BoxName.countryCode) == 'Jordan') {
          Get.to(() => AiPage());
        }
      }
      return googleUser;
    } catch (error) {
      return null;
    }
  }

  Future<GoogleSignInAccount?> signInFromLogin() async {
    try {
      final GoogleSignInAccount? googleUser =
          await _googleSignIn.authenticate();

      if (googleUser != null) {
        _cachedUser = googleUser; // حفظ الجلسة في الكاش المحلي
        await _handleSignUp(googleUser);

        final driverID =
            (box.read(BoxName.driverID)?.toString()) ?? 'Unknown ID';
        final emailDriver =
            (box.read(BoxName.emailDriver)?.toString()) ?? 'Unknown Email';

        print('Driver ID: $driverID');
        print('Driver Email: $emailDriver');

        await Get.find<LoginDriverController>()
            .loginWithGoogleCredential(driverID, emailDriver);
      }

      return googleUser;
    } catch (error, stackTrace) {
      mySnackeBarError('$error');
      CRUD.addError(error.toString(), stackTrace.toString(),
          'GoogleSignInAccount?> signInFromLogin()');
      return null;
    }
  }

  static Future<void> _handleSignUp(GoogleSignInAccount user) async {
    box.write(BoxName.driverID, (user.id) ?? 'Unknown ID');
    box.write(BoxName.emailDriver, (user.email) ?? 'Unknown Email');
  }

  static Future<void> signOut() async {
    try {
      await _googleSignIn.signOut();
    } catch (error) {
      // التعامل مع الخطأ بصمت إذا كانت جلسة جوجل فارغة مسبقاً
    } finally {
      _cachedUser = null; // مسح الكاش المحلي بشكل إلزامي
      await _handleSignOut();
    }
  }

  static Future<void> _handleSignOut() async {
    box.erase();
    storage.deleteAll();
    Get.offAll(OnBoardingPage());
  }

  // استخدام الكاش المحلي بدلاً من استدعاء المكتبة
  static GoogleSignInAccount? getCurrentUser() {
    return _cachedUser;
  }
}
