import 'dart:developer';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:injectable/injectable.dart';
import 'package:krow/core/data/static/email_validation_constants.dart';
import 'package:krow/features/profile/email_verification/domain/bloc/email_verification_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';

@injectable
class EmailVerificationService {
  static const recentLoginRequired = 'requires-recent-login';
  static const reLoginRequired = 'requires-re-login';
  static const tokenExpired = 'user-token-expired';

  final FirebaseAuth _auth = FirebaseAuth.instance;
  String? _currentUserPhone;

  String get currentUserPhone {
    _currentUserPhone ??= _auth.currentUser?.phoneNumber;

    return _currentUserPhone ?? '';
  }

  Future<void> sendVerificationEmail({required String email}) async {
    log('Sending email verification $email');

    await _auth.currentUser?.verifyBeforeUpdateEmail(
      email,
      // TODO: Enabling this code will require enabling Firebase Dynamic Links.
      // ActionCodeSettings(
      //   url: 'https://staging.app.krow.develop.express/emailLinkAuth/',
      // androidPackageName: dotenv.get('ANDROID_PACKAGE'),
      // iOSBundleId: dotenv.get('IOS_BUNDLE_ID'),
      // androidInstallApp: true,
      // handleCodeInApp: true,
      // linkDomain: 'krow-staging.firebaseapp.com',
      // ),
    );

    final sharedPrefs = await SharedPreferences.getInstance();

    sharedPrefs.setString(
      EmailValidationConstants.storedEmailKey,
      email,
    );
  }

  bool checkEmailForVerification({required String email}) {
    final user = _auth.currentUser;

    if (user == null || user.email == null) return false;

    return email == user.email && user.emailVerified;
  }

  Future<bool> isUserEmailVerified({
    required String newEmail,
  }) async {
    await _auth.currentUser?.reload();
    final user = _auth.currentUser;

    log(
      'Current user email: ${user?.email}, '
      'verified: ${user?.emailVerified}, '
      'Expected email: $newEmail',
    );
    if (user == null) {
      throw FirebaseAuthException(code: reLoginRequired);
    }
    return (user.emailVerified) && user.email == newEmail;
  }

  ReAuthRequirement isReAuthenticationRequired(String errorCode) {
    return switch (errorCode) {
      recentLoginRequired => ReAuthRequirement.recent,
      reLoginRequired || tokenExpired => ReAuthRequirement.immediate,
      _ => ReAuthRequirement.none,
    };
  }
}
