import 'package:e_commerce_training/res/R.dart';
import 'package:e_commerce_training/src/model/preference/app_preference.dart';
import 'package:e_commerce_training/src/model/repository/app_repository.dart';
import 'package:e_commerce_training/src/model/request/login_request.dart';
import 'package:e_commerce_training/src/model/request/register_request.dart';
import 'package:e_commerce_training/src/model/response/common_response.dart';
import 'package:e_commerce_training/src/model/response/login_response.dart';
import 'package:e_commerce_training/src/model/response/user_response.dart';
import 'package:e_commerce_training/src/model/service/api_result.dart';
import 'package:e_commerce_training/src/model/service/network_exceptions.dart';
import 'package:e_commerce_training/src/page/sign_up/sign_up_state.dart';
import 'package:e_commerce_training/src/util/const.dart';
import 'package:e_commerce_training/src/util/logger.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:e_commerce_training/src/util/validator.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:easy_localization/easy_localization.dart';

class SignUpCubit extends Cubit<SignUpState> with Validators {
  final AppRepository repository;
  String? errorPhone;
  String? errorEmail;
  String? errorName;
  String? errorPass;
  String? errorConfirmPass;
  bool isRuleChecked = false;

  SignUpCubit(this.repository) : super(InitialSignUpState());

  void validatePhoneNumber(String phoneNumber) {
    emit(InitialSignUpState());
    errorPhone = checkPhoneNumber(phoneNumber);
    emit(ValidateError());
  }

  void validateEmail(String email) {
    emit(InitialSignUpState());
    errorEmail = checkEmail2(email);
    emit(ValidateError());
  }

  void validateName(String name) {
    emit(InitialSignUpState());
    errorName = checkName(name);
    emit(ValidateError());
  }

  void validatePassword(String passWord) {
    emit(InitialSignUpState());
    errorPass = checkPass(passWord);
    emit(ValidateError());
  }

  void validateConfirmPassword(String pass, String confirmPass) {
    emit(InitialSignUpState());
    errorConfirmPass = checkRePass(pass, confirmPass);
    emit(ValidateError());
  }

  // void ruleCheck() {
  //   emit(InitialSignUpState());
  //   isRuleChecked = !isRuleChecked;
  //   emit(CheckBoxState());
  // }

  Future<void> signUp({
    String? name,
    String? email,
    String? password,
    String? phoneNumber,
    String? passwordConfirmation,
  }) async {
    emit(SignUpLoading());
    errorName = checkName(name!);
    errorPhone = checkPhoneNumber(phoneNumber!);
    errorEmail = checkEmail2(email!);
    errorPass = checkPass(password!);
    errorConfirmPass = checkRePass(password, passwordConfirmation!);
    if (!Util.isEmpty(errorName)) {
      emit(SignUpFailure(errorName));
      return;
    }
    if (!Util.isEmpty(errorPhone)) {
      emit(SignUpFailure(errorPhone));
      return;
    }
    if (!Util.isEmpty(errorEmail)) {
      emit(SignUpFailure(errorEmail));
      return;
    }
    if (!Util.isEmpty(errorPass)) {
      emit(SignUpFailure(errorPass));
      return;
    }
    if (!Util.isEmpty(errorConfirmPass)) {
      emit(SignUpFailure(errorConfirmPass));
      return;
    }
    // if (!isRuleChecked) {
    //   emit(SignUpFailure(R.string.please_accept_rule));
    //   return;
    // }
    ApiResult<LoginResponse> apiResult = await repository.register(
      RegisterRequest(
        fullName: name,
        phoneNumber: phoneNumber,
        email: email,
        password: password,
        confirmPassword: passwordConfirmation,
        deviceToken: "",
        referencesCode: "",
      ),
    );
    apiResult.when(success: (LoginResponse data) async {
      appPreference.setData(Const.TOKEN, data.data);
      if (data.isSuccess == true) {
        getDetailUser(data.message);
      } else {
        emit(SignUpFailure(R.string.login_failure.tr()));
      }
    }, failure: (NetworkExceptions error) async {
      emit(SignUpFailure(NetworkExceptions.getErrorMessage(error)));
      // Fake login response
      try {
        LoginResponse data = LoginResponse.fromJson(await Util.parseJson("common.json"));
        appPreference.setData(Const.TOKEN, data.data);
        if (data.isSuccess == true) {
          getDetailUser(data.message);
        } else {
          emit(SignUpFailure(R.string.login_failure.tr()));
        }
      } catch (e) {
        logger.e(e);
      }
    });
  }

  void getDetailUser(String? message) async {
    ApiResult<UserData> userResult = await repository.getDetailUser();
    userResult.when(success: (UserData data) {
      appPreference.saveData(data);
      emit(SignUpSuccess(message: message));
    }, failure: (NetworkExceptions error) async {
      emit(SignUpFailure(NetworkExceptions.getErrorMessage(error)));
      // Fake get detail user response
      try {
        UserResponse userResponse = UserResponse.fromJson(await Util.parseJson("user.json"));
        if (userResponse.data != null) {
          appPreference.saveData(userResponse.data!);
          emit(SignUpSuccess(message: message));
        }
      } catch (e) {
        logger.e(e);
      }
    });
  }
}
