import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
// import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:initial_folder/helper/user_info.dart';
import 'package:initial_folder/models/user_model.dart';
import 'package:initial_folder/services/auth_service.dart';

class FirebaseAuthenticationProvider extends ChangeNotifier {
  final googleSignIn = GoogleSignIn();
  GoogleSignInAccount? _user;
  GoogleSignInAccount get user => _user!;

  UserModel? _userModel;
  UserModel? get userModel => _userModel;

  set userModel(UserModel? userModel) {
    _userModel = userModel;
    notifyListeners();
  }

  Future googleSignUp() async {
    final googleUser = await googleSignIn.signIn();
    if (googleUser == null) return;
    _user = googleUser;
    final googleAuth = await googleUser.authentication;
    final credential =
        GoogleAuthProvider.credential(accessToken: googleAuth.idToken);
    await FirebaseAuth.instance.signInWithCredential(credential);
    await AuthService().googleSignInAuth(
      idToken: googleAuth.idToken ?? '',
      // email: googleUser.email,
      // password: '',
    );
    // _userModel = userModel;
    await UsersInfo().setEmail(googleUser.email);
    notifyListeners();
    return true;
  }

  Future<bool> googleLogin() async {
    try {
      print('Preparing');
      final googleUser = await googleSignIn.signIn();
      print('Start');
      if (googleUser == null) {
        print('Failed');
        await logout();
        return false;
      }

      print('State 1');
      final GoogleSignInAuthentication googleAuth =
          await googleUser.authentication;

      final credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      print('State 2');
      final userCredential =
          await FirebaseAuth.instance.signInWithCredential(credential);

      print("ID Token: ${googleAuth.idToken}");

      await AuthService().googleSignInAuth(
        idToken: googleAuth.idToken ?? '',
      );
      // _userModel = userModel;

      print('State 3');
      await UsersInfo().setEmail(googleUser.email);

      print('Login sukses');
      notifyListeners();
      return true;
    } catch (e) {
      // print(e);
      // return false;
      if (e.toString() == 'Exception: Akun anda belum terdaftar') {
        await logout();
        throw Exception('Akun anda belum terdaftar');
      } else {
        print(e);
        await logout();
        return false;
      }
    }
  }

  // Future facebookLogin() async {
  //   try {
  //     final LoginResult facebookSignIn = await FacebookAuth.instance.login();
  //     if (facebookSignIn.accessToken == null) {
  //       await logout();
  //       return false;
  //     }
  //     switch (facebookSignIn.status) {
  //       case LoginStatus.success:
  //         try {
  //           final facebookAuthCredential = FacebookAuthProvider.credential(
  //               facebookSignIn.accessToken!.token);
  //           await FirebaseAuth.instance
  //               .signInWithCredential(facebookAuthCredential);

  //           String name = await FacebookAuth.instance
  //               .getUserData()
  //               .then((data) => data['name']);
  //           String email = await FacebookAuth.instance
  //               .getUserData()
  //               .then((data) => data['email']);
  //           String pictureUrl = await FacebookAuth.instance
  //               .getUserData()
  //               .then((data) => data['picture']['data']['url']);

  //           UserModel userModel = await AuthService().facebookSignInAuth(
  //             name: name,
  //             email: email,
  //             password: '',
  //             pictureUrl: pictureUrl,
  //           );
  //           _userModel = userModel;

  //           await UsersInfo().setEmail(email);

  //           notifyListeners();
  //           return true;
  //         } catch (e) {
  //           await logout();
  //           return false;
  //         }
  //       case LoginStatus.cancelled:
  //         await logout();
  //         return false;
  //       case LoginStatus.failed:
  //         await logout();
  //         return false;
  //       default:
  //         await logout();
  //         return false;
  //     }
  //   } catch (e) {
  //     await logout();
  //     return false;
  //   }
  // }

  Future logout() async {
    try {
      if (googleSignIn.currentUser != null) {
        await googleSignIn.disconnect();
      } // else if (await FacebookAuth.instance.accessToken != null) {
      //   await FacebookAuth.instance.logOut();
      // }
    } finally {
      FirebaseAuth.instance.signOut();
      notifyListeners();
    }
  }
}
