import 'package:aitrainer_app/model/cache.dart';
import 'package:aitrainer_app/service/logging.dart' as logging;
import 'package:apple_sign_in/apple_sign_in.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';

class FirebaseApi with logging.Logging {
  bool appleSignInAvailable = false;
  //late FirebaseApi _instance;

  static final FirebaseAuth auth = FirebaseAuth.instance;

  static const String SIGN_IN_OK = "OK";
  static const String SIGN_IN_NOT_FOUND = "user-not-found";
  static const String SIGN_IN_WRONG_PWD = "wrong-password";
  static const String REGISTER_WEAK_PWD = "weak-password";
  static const String REGISTER_EMAIL_IN_USE = "email-already-in-use";

  late UserCredential userCredential;

  factory FirebaseApi() => FirebaseApi._internal();

  FirebaseApi._internal();

  // Define an async function to initialize FlutterFire
  Future<void> initializeFlutterFire() async {
    try {
      // Wait for Firebase to initialize and set `_initialized` state to true
      FirebaseApp app = await Firebase.initializeApp();

      this.appleSignInAvailable = await AppleSignIn.isAvailable();
    } catch (e) {
      // Set `_error` state to true if Firebase initialization fails
      log("Error initializing Firebase");
    }
  }

  Future<String> signInEmail(String? email, String? password) async {
    if (email == null) {
      throw Exception("Please type an email address");
    }
    if (password == null) {
      throw Exception("Password too short");
    }
    String rc = SIGN_IN_OK;
    try {
      userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(email: email, password: password);
      Cache().firebaseUid = userCredential.user!.uid;
    } on FirebaseAuthException catch (e) {
      if (e.code == 'user-not-found') {
        log('No user found for that email.');
        rc = SIGN_IN_NOT_FOUND;
      } else if (e.code == 'wrong-password') {
        log('Wrong password provided for that user.');
        rc = SIGN_IN_WRONG_PWD;
        throw Exception("Customer does not exist or the password is wrong");
      }
      return e.code;
    }
    return rc;
  }

  Future<String> registerEmail(String email, String password) async {
    String rc = SIGN_IN_OK;
    try {
      userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: email, password: password);
      Cache().firebaseUid = userCredential.user!.uid;
    } on FirebaseAuthException catch (e) {
      if (e.code == 'weak-password') {
        log('The password provided is too weak.');
        rc = REGISTER_WEAK_PWD;
        throw Exception("Password too short");
      } else if (e.code == 'email-already-in-use') {
        log('The account already exists for that email.');
        rc = REGISTER_EMAIL_IN_USE;
        throw Exception("The email address has been registered already");
      }
    } catch (e) {
      log(e.toString());
      throw Exception(e.toString());
    }
    return rc;
  }

  Future<Map<String, dynamic>> signInWithApple() async {
    Map<String, dynamic> userData = Map();

    final AuthorizationResult result = await AppleSignIn.performRequests([
      AppleIdRequest(requestedScopes: [Scope.email, Scope.fullName])
    ]);
    switch (result.status) {
      case AuthorizationStatus.authorized:
        print('User authorized');
        break;
      case AuthorizationStatus.error:
        print('User error');
        throw Exception("Apple Sign-In failed");
      case AuthorizationStatus.cancelled:
        print('User cancelled');
        throw Exception("Apple Sign-In cancelled");
    }

    // Create an `OAuthCredential` from the credential returned by Apple.
    final oauthCredential = OAuthProvider("apple.com").credential(
        idToken: String.fromCharCodes(result.credential.identityToken),
        accessToken: String.fromCharCodes(result.credential.authorizationCode));

    // Sign in the user with Firebase. If the nonce we generated earlier does
    // not match the nonce in `appleCredential.identityToken`, sign in will fail.
    UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(oauthCredential);
    Cache().firebaseUid = userCredential.user!.uid;
    log("userCredential: " + userCredential.toString());

    log("Apple Credentials: " +
        result.credential.user.toString() +
        " state " +
        result.credential.state.toString() +
        " email " +
        userCredential.user!.email!);
    userData['email'] = userCredential.user!.email;

    return userData;
  }

  Future<Map<String, dynamic>> registerWithApple() async {
    Map<String, dynamic> userData = Map();
    final AuthorizationResult result = await AppleSignIn.performRequests([
      AppleIdRequest(requestedScopes: [Scope.email, Scope.fullName])
    ]);
    switch (result.status) {
      case AuthorizationStatus.authorized:
        print('Apple User authorized');
        break;
      case AuthorizationStatus.error:
        print('Apple User error');
        throw Exception("Apple Sign-In failed");
      case AuthorizationStatus.cancelled:
        print('User cancelled');
        throw Exception("Apple Sign-In cancelled");
    }

    // Create an `OAuthCredential` from the credential returned by Apple.
    final oauthCredential = OAuthProvider("apple.com").credential(
        idToken: String.fromCharCodes(result.credential.identityToken),
        accessToken: String.fromCharCodes(result.credential.authorizationCode));

    // Sign in the user with Firebase. If the nonce we generated earlier does
    // not match the nonce in `appleCredential.identityToken`, sign in will fail.
    UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(oauthCredential);

    Cache().firebaseUid = userCredential.user!.uid;

    userData['email'] = userCredential.user!.email;

    return userData;
  }

  Future<Map<String, dynamic>> signInWithGoogle() async {
    Map<String, dynamic> userData = Map();

    // Trigger the authentication flow
    GoogleSignIn _googleSignIn = GoogleSignIn(
      scopes: [
        'email',
        'https://www.googleapis.com/auth/contacts.readonly',
      ],
    );
    final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();

    if (googleUser == null) {
      throw Exception("Google Sign In failed");
    }

    // Obtain the auth details from the request
    final GoogleSignInAuthentication googleAuth = await googleUser.authentication;

    // Create a new credential
    final OAuthCredential credential = GoogleAuthProvider.credential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

    UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(credential);
    Cache().firebaseUid = userCredential.user!.uid;

    log("GoogleUser: " + googleUser.toString());
    userData['email'] = googleUser.email;
    userData['id'] = googleUser.id;
    userData['name'] = googleUser.displayName;

    return userData;
  }

  Future<Map<String, dynamic>> registerWithGoogle() async {
    Map<String, dynamic> userData = Map();

    // Trigger the authentication flow
    GoogleSignIn _googleSignIn = GoogleSignIn(
      scopes: [
        'email',
        'https://www.googleapis.com/auth/contacts.readonly',
      ],
    );
    final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();

    if (googleUser == null) {
      throw Exception("Google Sign In failed");
    }

    // Obtain the auth details from the request
    final GoogleSignInAuthentication googleAuth = await googleUser.authentication;

    // Create a new credential
    final OAuthCredential credential = GoogleAuthProvider.credential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

    final userCredential = await FirebaseAuth.instance.signInWithCredential(credential);

    log("Google credentials: " + credential.toString() + " GoogleUser: " + googleUser.toString());
    Cache().firebaseUid = userCredential.user!.uid;

    userData['email'] = googleUser.email;

    return userData;
  }

  Future<Map<String, dynamic>> signInWithFacebook() async {
    Map<String, dynamic> userData;

    // by default the login method has the next permissions ['email','public_profile']
    final LoginResult result = await FacebookAuth.instance.login();
    if (result.status == LoginStatus.success) {
      final AccessToken accessToken = result.accessToken!;
      log(accessToken.toJson().toString());
      Cache().accessTokenFacebook = accessToken;
      // get the user data
      userData = await FacebookAuth.instance.getUserData();
      Cache().firebaseUid = userData['id'];
      log(userData.toString());
    } else {
      throw Exception("Facebook login was not successful");
    }

    return userData;
  }

  Future<Map<String, dynamic>> registerWithFacebook() async {
    Map<String, dynamic> userData;

    // by default the login method has the next permissions ['email','public_profile']
    final LoginResult result = await FacebookAuth.instance.login();
    if (result.status == LoginStatus.success) {
      final AccessToken accessToken = result.accessToken!;
      Cache().accessTokenFacebook = accessToken;
      // get the user data
      userData = await FacebookAuth.instance.getUserData();
      log("FB user data: " + userData.toString());

      // Create a credential from the access token
      final OAuthCredential facebookAuthCredential = FacebookAuthProvider.credential(accessToken.token);

      // Once signed in, return the UserCredential
      final userCredential = await FirebaseAuth.instance.signInWithCredential(facebookAuthCredential);
      log("Email by FB: " + userData['email'] + " FB credential: " + userCredential.toString());

      Cache().firebaseUid = userCredential.user!.uid;
    } else {
      throw Exception("Facebook login was not successful");
    }

    return userData;
  }

  Future<void> logOutFacebook() async {
    await FacebookAuth.instance.logOut();
    Cache().accessTokenFacebook = null;
  }

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

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

  Future<void> setupRemoteConfig() async {
    initializeFlutterFire();
    final RemoteConfig remoteConfig = RemoteConfig.instance;
    await remoteConfig.setConfigSettings(RemoteConfigSettings(
      fetchTimeout: const Duration(seconds: 10),
      minimumFetchInterval: const Duration(seconds: 1),
    ));
    await remoteConfig.setDefaults(<String, dynamic>{
      'sales_page_text': '0',
      'sales_page_bkg': 'dark',
      'sales_page_offer': 'monthly',
      'please_log_in': '',
    });
    RemoteConfigValue(null, ValueSource.valueStatic);
    Cache().setRemoteConfig(remoteConfig);

    Map config = remoteConfig.getAll();
    print("RemoteConfig sales_page_text Value : ${config['sales_page_text'].asString()}");
  }
}
