import 'package:auto_route/auto_route.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import '../../infrastructure/models/data/user_data.dart';
import '../../presentation/routes/app_router.gr.dart';
import 'sign_up_state.dart';
import '../../domain/interface/interfaces.dart';
import '../../infrastructure/services/services.dart';

class SignUpNotifier extends StateNotifier<SignUpState> {
  final AuthRepository _authRepository;
  final UsersRepository _userRepository;

  SignUpNotifier(this._authRepository, this._userRepository)
      : super(const SignUpState());

  Future<void> getProfileDetails() async {
    final response = await _userRepository.getProfileDetails();
    response.when(
      success: (data) {
        LocalStorage.instance.setUser(data.data);
        if (data.data?.wallet != null) {
          LocalStorage.instance.setWallet(data.data?.wallet);
        }
      },
      failure: (failure, status) {
        debugPrint('==> get profile details failure: $failure');
      },
    );
  }

  Future<void> checkPhone({required VoidCallback onSuccess , required BuildContext context}) async {
    state = state.copyWith(isLoading: true);
    final response = await _userRepository.checkPhone(state.phone);
    response.when(
      success: (data) {
        if(!data) {
          onSuccess.call();
        }
        else {
          state = state.copyWith(isLoading: false);
          AppHelpers.showCheckTopSnackBar(context ,  text: AppHelpers.trans(TrKeys.userExist),);
        }

      },
      failure: (failure, status) {
        state = state.copyWith(isLoading: false);
        debugPrint('==> get profile details failure: $failure');
      },
    );
  }

  void setPassword(String password) {
    state = state.copyWith(password: password.trim(), isPasswordInvalid: false);
  }

  void setConfirmPassword(String password) {
    state = state.copyWith(
      confirmPassword: password.trim(),
      isConfirmPasswordInvalid: false,
    );
  }

  void setFirstName(String name) {
    state = state.copyWith(
      firstName: name.trim(),
      isFirstNameInvalid: false,
    );
  }

  void setEmail(String value) {
    state = state.copyWith(email: value.trim(), isEmailInvalid: false);
  }

  void toggleShowPassword() {
    state = state.copyWith(showPassword: !state.showPassword);
  }

  void toggleKeepLogin() {
    state = state.copyWith(isKeepLogin: !state.isKeepLogin);
  }

  checkEmail() {
    return AppValidators.isValidEmail(state.email);
  }

  Future<void> sendCode(BuildContext context, VoidCallback onSuccess) async {
    final connected = await AppConnectivity.connectivity();
    if (connected) {
      if (AppValidators.emptyCheck(state.phone) == null) {
        state = state.copyWith(isPhoneInvalid: true);
        return;
      }
      state = state.copyWith(isLoading: true, isSuccess: false);
      final response = await _authRepository.signUp(
        phone: state.phone,
      );
      response.when(
        success: (data) async {
          state = state.copyWith(isLoading: false, isSuccess: true);
          onSuccess();
        },
        failure: (failure, status) {
          state = state.copyWith(isLoading: false, isSuccess: false);
          if (status == 400) {
            AppHelpers.showCheckTopSnackBar(
              context,
              text: AppHelpers.trans(TrKeys.emailIsNotValid),
            );
          } else {
            AppHelpers.showCheckTopSnackBar(
              context,
              text: failure.toString(),
            );
          }
        },
      );
    } else {
      if (mounted) {
        AppHelpers.showNoConnectionSnackBar(context);
      }
    }
  }

  Future<void> sendCodeToNumber(
      BuildContext context, ValueChanged<String> onSuccess) async {
    final connected = await AppConnectivity.connectivity();

    if (connected) {
      if (AppValidators.emptyCheck(state.phone)?.isNotEmpty ?? false) {
        state = state.copyWith(isEmailInvalid: true);
        return;
      }
      state = state.copyWith(isLoading: true, isSuccess: false);
      await FirebaseAuth.instance.verifyPhoneNumber(
        phoneNumber: state.phone,
        verificationCompleted: (PhoneAuthCredential credential) {},
        verificationFailed: (FirebaseAuthException e) {
          AppHelpers.showCheckTopSnackBar(context, text: e.message);
          state = state.copyWith(isLoading: false, isSuccess: false);
        },
        codeSent: (String verificationId, int? resendToken) {
          state = state.copyWith(
            verificationId: verificationId,
            phone: state.phone,
            isLoading: false,
            isSuccess: true,
          );
          onSuccess(verificationId);
        },
        codeAutoRetrievalTimeout: (String verificationId) {},
      );
    } else {
      if (mounted) {
        AppHelpers.showNoConnectionSnackBar(context);
      }
    }
  }

  void setPhone(String value) {
    state = state.copyWith(
      phone: value,
      isPhoneInvalid: false,
    );
  }

  void setLatName(String name) {
    state = state.copyWith(
      lastName: name.trim(),
      isSurNameInvalid: false,
    );
  }

  void setReferral(String name) {
    state = state.copyWith(referral: name.trim());
  }

  void toggleShowConfirmPassword() {
    state = state.copyWith(showConfirmPassword: !state.showConfirmPassword);
  }

  Future<void> registerWithPhone(BuildContext context , String phone) async {
    final connected = await AppConnectivity.connectivity();
    state = state.copyWith(isPasswordInvalid: false);
    if (connected) {
      if (AppValidators.emptyCheck(state.email)?.isNotEmpty ?? false) {
        state = state.copyWith(isEmailInvalid: true);
        return;
      }
      if (AppValidators.emptyCheck(state.firstName)?.isNotEmpty ?? false) {
        state = state.copyWith(isFirstNameInvalid: true);
        return;
      }
      if (AppValidators.emptyCheck(state.lastName)?.isNotEmpty ?? false) {
        state = state.copyWith(isSurNameInvalid: true);
        return;
      }
      if (!AppValidators.isValidPassword(state.password)) {
        state = state.copyWith(isPasswordInvalid: true);
        return;
      }
      if (!AppValidators.isValidConfirmPassword(
          state.password, state.confirmPassword)) {
        state = state.copyWith(isConfirmPasswordInvalid: true);
        return;
      }
      state = state.copyWith(isLoading: true);
      final response = await _authRepository.sigUpWithData(
          user: UserData(
              email: state.email,
              firstname: state.firstName,
              lastname: state.lastName,
              phone: phone,
              password: state.password,
              confirmPassword: state.confirmPassword,));

      response.when(
        success: (data) async {
          state = state.copyWith(
            isLoading: false,
          );
          LocalStorage.instance.setToken(data.token);
          context.replaceRoute(const CreateShopRoute());
          String? fcmToken = await FirebaseMessaging.instance.getToken();
          _userRepository.updateFirebaseToken(fcmToken);
        },
        failure: (failure, status) {
          state = state.copyWith(isLoading: false);
          if (status == 400) {
            AppHelpers.showCheckTopSnackBar(
              context,
              text: "error",
            );
          } else {
            AppHelpers.showCheckTopSnackBar(
              context,
              text: "error",
            );
          }
        },
      );
    } else {
      if (mounted) {
        AppHelpers.showNoConnectionSnackBar(context);
      }
    }
  }
}
