import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart';
import 'package:travel_mate/services/error_service.dart';

class AuthService {
  final _errorService = ErrorService();
  final FirebaseAuth firebaseAuth = FirebaseAuth.instance;

  User? get currentUser => firebaseAuth.currentUser;

  Stream<User?> get authStateChanges => firebaseAuth.authStateChanges();

  Future<UserCredential> signInWithEmailAndPassword({
    required String email,
    required String password
  }) async {
    return await firebaseAuth.signInWithEmailAndPassword(
        email: email, password: password);
  }

  Future<UserCredential> signUpWithEmailAndPassword({
      required String email, 
      required String password
    }) async {
    return await firebaseAuth.createUserWithEmailAndPassword(
        email: email, password: password);
  }

  Future<void> signOut() async {
    await firebaseAuth.signOut();
  }

  Future<void> resetPassword(String email) async {
    await firebaseAuth.sendPasswordResetEmail(email: email);
  }

  Future<void> updateDisplayName({
    required String displayName,
  }) async {
    await currentUser!.updateDisplayName(displayName);
  }

  Future<void> deleteAccount({
    required String password,
    required String email,
  }) async {
    // Re-authenticate the user
    AuthCredential credential =
        EmailAuthProvider.credential(email: email, password: password);
    await currentUser!.reauthenticateWithCredential(credential);

    // Delete the user
    await currentUser!.delete();
    await firebaseAuth.signOut();
  }

  Future<void> resetPasswordFromCurrentPassword({
    required String currentPassword,
    required String newPassword,
    required String email,
  }) async {
    // Re-authenticate the user
    AuthCredential credential =
        EmailAuthProvider.credential(email: email, password: currentPassword);
    await currentUser!.reauthenticateWithCredential(credential);

    // Update the password
    await currentUser!.updatePassword(newPassword);
  }

  Future<void> ensureInitialized(){
    return GoogleSignInPlatform.instance.init(const InitParameters());
  }

  Future<UserCredential> signInWithGoogle() async {
    try {
      await ensureInitialized();
      final AuthenticationResults result = await GoogleSignInPlatform.instance.authenticate(const AuthenticateParameters());
      final String? idToken = result.authenticationTokens.idToken;
      if (idToken == null) {
        throw FirebaseAuthException(
          code: 'ERROR_MISSING_GOOGLE_ID_TOKEN',
          message: 'Missing Google ID Token',
        );
      } else {
        final OAuthCredential credential = GoogleAuthProvider.credential(idToken: idToken);
        UserCredential userCredential = await firebaseAuth.signInWithCredential(credential);
        
        // Retourner le UserCredential au lieu de void
        return userCredential;
      }

    } on GoogleSignInException catch (e) {
      _errorService.logError('Erreur Google Sign-In: $e', StackTrace.current);
      rethrow;
    } on FirebaseAuthException catch (e) {
      _errorService.logError('Erreur Firebase lors de l\'initialisation de Google Sign-In: $e', StackTrace.current);
      rethrow;
    } catch (e) {
      _errorService.logError('Erreur inconnue lors de l\'initialisation de Google Sign-In: $e', StackTrace.current);
      rethrow;
    }
  }

  Future signInWithApple() async {
    // TODO: Implémenter la connexion avec Apple
  }
  
}