import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../constant/box_name.dart';
import '../../constant/links.dart';
import '../../main.dart';
import '../functions/crud.dart';
import '../../onbording_page.dart';
import 'login_controller.dart';

class GoogleSignInHelper {
  // ✅ GoogleSignIn singleton
  static final GoogleSignIn _signIn = GoogleSignIn.instance;

  static GoogleSignInAccount? _lastUser;

  /// 👇 استدعها في main() مرة واحدة
  static Future<void> init() async {
    await _signIn.initialize(
      serverClientId:
          '594687661098-2u640akrb3k7sak5t0nqki6f4v6hq1bq.apps.googleusercontent.com',
    );

    // Events listener
    _signIn.authenticationEvents.listen((event) async {
      if (event is GoogleSignInAuthenticationEventSignIn) {
        _lastUser = event.user;
        await _handleSignUp(event.user);
      } else if (event is GoogleSignInAuthenticationEventSignOut) {
        _lastUser = null;
      }
    });

    // silent login if possible
    try {
      await _signIn.attemptLightweightAuthentication();
    } catch (_) {}
  }

  /// ✅ تسجيل دخول عادي
  static Future<GoogleSignInAccount?> signIn() async {
    try {
      final user =
          await _signIn.authenticate(scopeHint: const ['email', 'profile']);
      if (user != null) {
        _lastUser = user;
        await _handleSignUp(user);

        // اطبع القيم (للتأكد)
        print("Google ID: ${user.id}");
        print("Email: ${user.email}");
        print("Name: ${user.displayName}");
        print("Photo: ${user.photoUrl}");
      }
      return user;
    } on PlatformException catch (e) {
      if (e.code == 'sign_in_required') {
        await showGooglePlayServicesError();
      }
      return null;
    } catch (e) {
      await addError("Google Sign-In error: $e", "signIn()");
      return null;
    }
  }

  /// ✅ تسجيل دخول مخصص لشاشة Login (مع استدعاء الكنترولر)
  static Future<GoogleSignInAccount?> signInFromLogin() async {
    await init();
    final user = await signIn();
    if (user != null) {
      await Get.put(LoginController()).loginUsingCredentials(
        box.read(BoxName.passengerID).toString(),
        box.read(BoxName.email).toString(),
      );
    }
    return user;
  }

  /// ✅ طلب سكوبات إضافية (بديل withScopes القديم)
  static Future<void> requestExtraScopes(List<String> scopes) async {
    final user = _lastUser;
    if (user == null) return;
    await user.authorizationClient.authorizeScopes(scopes);
  }

  /// ✅ تسجيل خروج
  static Future<void> signOut() async {
    await _signIn.signOut();
    await _handleSignOut();
  }

  static GoogleSignInAccount? getCurrentUser() => _lastUser;

  // ================= Helpers ==================

  static Future<void> _handleSignUp(GoogleSignInAccount user) async {
    box.write(BoxName.passengerID, user.id);
    box.write(BoxName.email, user.email);
    box.write(BoxName.name, user.displayName ?? '');
    box.write(BoxName.passengerPhotoUrl, user.photoUrl ?? '');
  }

  static Future<void> _handleSignOut() async {
    box.erase();

    Get.offAll(OnBoardingPage());
  }

  static Future<void> addError(String error, String where) async {
    await CRUD().post(link: AppLink.addError, payload: {
      'error': error,
      'userId': box.read(BoxName.driverID) ?? box.read(BoxName.passengerID),
      'userType': box.read(BoxName.driverID) != null ? 'Driver' : 'Passenger',
      'phone': box.read(BoxName.phone) ?? box.read(BoxName.phoneDriver),
      'device': where,
    });
  }

  static Future<void> showGooglePlayServicesError() async {
    const playStoreUrl =
        'https://play.google.com/store/apps/details?id=com.google.android.gms&hl=en_US';
    final uri = Uri.parse(playStoreUrl);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    } else {
      showDialog(
        context: Get.context!,
        builder: (context) => AlertDialog(
          title: Text('Error'.tr),
          content: Text(
            'Could not open the Google Play Store. Please update Google Play Services manually.'
                .tr,
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: Text('Close'.tr),
            ),
          ],
        ),
      );
    }
  }
}
