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(
    scopes: [
      'email',
      'profile',
    ],
  );

  // Method to handle Google Sign-In
  static Future<GoogleSignInAccount?> signIn() async {
    try {
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
      if (googleUser != null) {
        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.signIn();

      if (googleUser != null) {
        // Handle sign-up and store user information
        await _handleSignUp(googleUser);

        // Retrieve driverID and emailDriver with added validation
        final driverID =
            (box.read(BoxName.driverID)!.toString()) ?? 'Unknown ID';
        final emailDriver =
            (box.read(BoxName.emailDriver)!.toString()) ?? 'Unknown Email';

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

        // Check if driverID is a valid numeric string
        // if (driverID != 'Unknown ID' && int.tryParse(driverID) != null) {
        await Get.find<LoginDriverController>()
            .loginWithGoogleCredential(driverID, emailDriver);
        // }
        //  else {
        //   print('Invalid driverID format: $driverID');
        //   Get.snackbar('Login Error', 'Invalid driver ID format.',
        //       backgroundColor: AppColor.redColor);
        // }
      }

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

  static Future<void> _handleSignUp(GoogleSignInAccount user) async {
    // Store driver information
    box.write(BoxName.driverID,
        (user.id) ?? 'Unknown ID'); // Ensure there's a fallback value
    box.write(BoxName.emailDriver, (user.email) ?? 'Unknown Email');
  }

  // Method to handle Google Sign-Out
  static Future<void> signOut() async {
    try {
      await _googleSignIn.signOut();
      await _handleSignOut();
    } catch (error) {}
  }

  static Future<void> _handleSignOut() async {
    // Clear stored driver information
    box.erase();
    storage.deleteAll();
    Get.offAll(OnBoardingPage());
    // Perform any additional sign-out tasks or API calls here
    // For example, you can notify your server about the user sign-out
  }

  // Method to get the current signed-in user
  static GoogleSignInAccount? getCurrentUser() {
    return _googleSignIn.currentUser;
  }
}
// import 'dart:async';
// import 'dart:async';
// import 'dart:convert';
// import 'package:flutter/material.dart';
// import 'package:get/get.dart';
// import 'package:http/http.dart' as http;
// import 'package:sefer_driver/constant/box_name.dart';
// import 'package:sefer_driver/controller/auth/captin/login_captin_controller.dart';
// import 'package:sefer_driver/main.dart';
// import 'package:sefer_driver/views/auth/captin/ai_page.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:url_launcher/url_launcher.dart';

// import '../functions/add_error.dart';

// /// Helper class to manage Google Sign-In via an external browser and polling.
// class GoogleSignInHelper {
//   // URLs for your server endpoints
//   static const String _startLoginUrl =
//       'https://api.tripz-egypt.com/tripz/auth/google_auth/login.php';
//   static const String _checkStatusUrl =
//       'https://api.tripz-egypt.com/tripz/auth/google_auth/check_status.php';

//   static Future<void> _initiateSignIn(
//       Function(Map<String, dynamic> userData) onSignInSuccess) async {
//     try {
//       // Show a loading dialog to the user
//       Get.dialog(
//         const Center(
//           child: Material(
//             color: Colors.transparent,
//             child: Column(
//               mainAxisSize: MainAxisSize.min,
//               children: [
//                 CircularProgressIndicator(),
//                 SizedBox(height: 16),
//                 Text(
//                   "Waiting for browser sign-in...",
//                   style: TextStyle(color: Colors.white, fontSize: 16),
//                 ),
//               ],
//             ),
//           ),
//         ),
//         barrierDismissible: false,
//       );

//       // 1. Get the auth URL and login token from the server
//       final startResponse = await http.get(Uri.parse(_startLoginUrl));
//       if (startResponse.statusCode != 200) {
//         throw Exception('Failed to start login process.');
//       }

//       final startData = jsonDecode(startResponse.body);
//       final String authUrl = startData['authUrl'];
//       final String loginToken = startData['loginToken'];

//       // 2. Launch the URL in an external browser
//       if (!await launchUrl(Uri.parse(authUrl),
//           mode: LaunchMode.externalApplication)) {
//         throw Exception('Could not launch browser.');
//       }

//       // 3. Start polling the server for status
//       await _startPolling(loginToken, onSignInSuccess);
//     } catch (e) {
//       addError(e.toString(), '_initiateSignIn');
//       mySnackeBarError('Sign-in failed: ${e.toString()}');
//       // Close the loading dialog on error
//       if (Get.isDialogOpen ?? false) {
//         Get.back();
//       }
//     }
//   }

//   static Future<void> _startPolling(String loginToken,
//       Function(Map<String, dynamic> userData) onSignInSuccess) async {
//     Timer? poller;
//     const int maxAttempts = 30; // Poll for 60 seconds (30 attempts * 2s)
//     int attempts = 0;

//     poller = Timer.periodic(const Duration(seconds: 2), (timer) async {
//       if (attempts >= maxAttempts) {
//         timer.cancel();
//         if (Get.isDialogOpen ?? false) Get.back();
//         mySnackeBarError('Sign-in timed out. Please try again.');
//         return;
//       }

//       attempts++;

//       try {
//         final statusResponse = await http.post(
//           Uri.parse(_checkStatusUrl),
//           headers: {'Content-Type': 'application/json'},
//           body: jsonEncode({'loginToken': loginToken}),
//         );

//         if (statusResponse.statusCode == 200) {
//           final statusData = jsonDecode(statusResponse.body);
//           if (statusData['status'] == 'success') {
//             timer.cancel();
//             if (Get.isDialogOpen ?? false) Get.back();
//             // Success!
//             onSignInSuccess(statusData['userData']);
//           }
//           // If status is 'pending', do nothing and wait for the next poll.
//         }
//       } catch (e) {
//         // Handle polling errors silently or log them
//         debugPrint("Polling error: $e");
//       }
//     });
//   }

//   /// Triggers the sign-in process for a new user.
//   static Future<void> signIn() async {
//     await _initiateSignIn((userData) async {
//       debugPrint('Sign-in success data: $userData');
//       await _handleSignUp(userData);
//       if (box.read(BoxName.countryCode) == 'Egypt') {
//         Get.offAll(() => SmsSignupEgypt());
//       } else if (box.read(BoxName.countryCode) == 'Jordan') {
//         Get.offAll(() => AiPage());
//       }
//     });
//   }

//   /// Triggers the sign-in process for an existing user.
//   static Future<void> signInFromLogin() async {
//     await _initiateSignIn((userData) async {
//       debugPrint('Sign-in from login success data: $userData');
//       await _handleSignUp(userData);

//       final driverID = userData['id']?.toString() ?? 'Unknown ID';
//       final emailDriver = userData['email']?.toString() ?? 'Unknown Email';

//       debugPrint('Driver ID from server: $driverID');
//       debugPrint('Driver Email from server: $emailDriver');

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

//   /// Stores user information received from the server.
//   static Future<void> _handleSignUp(Map<String, dynamic> userData) async {
//     box.write(BoxName.driverID, userData['id'] ?? 'Unknown ID');
//     box.write(BoxName.emailDriver, userData['email'] ?? 'Unknown Email');
//   }

//   /// Clears local data.
//   static Future<void> signOut() async {
//     box.remove(BoxName.driverID);
//     box.remove(BoxName.emailDriver);
//     box.remove(BoxName.lang);
//     box.remove(BoxName.nameDriver);
//     box.remove(BoxName.passengerID);
//     box.remove(BoxName.phoneDriver);
//     box.remove(BoxName.tokenFCM);
//     box.remove(BoxName.tokens);
//     box.remove(BoxName.carPlate);
//     box.remove(BoxName.lastNameDriver);
//     box.remove(BoxName.agreeTerms);
//     box.remove(BoxName.tokenDriver);
//     box.remove(BoxName.countryCode);
//     box.remove(BoxName.accountIdStripeConnect);
//     box.remove(BoxName.phoneVerified);
//     Get.offAll(() => OnBoardingPage());
//   }
// }
