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/response/common_response.dart';
import 'package:e_commerce_training/src/util/logger.dart';
import 'package:easy_localization/easy_localization.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/login/login_state.dart';
import 'package:e_commerce_training/src/util/const.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:e_commerce_training/src/util/validator.dart';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LoginCubit extends Cubit<LoginState> with Validators {
  final AppRepository repository;
  String? errorPhone, errorEmail, errorPass;
  bool _isRememberPassword = true;

  // String get phone => _pref.getString(Const.PHONE) ?? "";
  //
  // String get email => _pref.getString(Const.PHONE) ?? "";

  bool get isRememberPassword => _isRememberPassword;

  LoginCubit(this.repository) : super(LoginInitial());

  void login(String phone, String password) async {
    emit(LoginLoading());
    String? errorPhone = checkPhoneNumber(phone);
    String? errorPass = checkPass(password);
    if (!Util.isEmpty(errorPhone)) {
      emit(LoginFailure(errorPhone));
      return;
    }
    if (!Util.isEmpty(errorPass)) {
      emit(LoginFailure(errorPass));
      return;
    }
    ApiResult<LoginResponse> apiResult = await repository.login(
      LoginRequest(
        phoneNumber: phone,
        password: password,
        deviceToken: "",
      ),
    );
    apiResult.when(success: (LoginResponse data) async {
      appPreference.setData(Const.TOKEN, data.data);
      if (data.isSuccess == true) {
        getDetailUser(data.message);
      } else {
        emit(LoginFailure(R.string.login_failure.tr()));
      }
    }, failure: (NetworkExceptions error) async {
      emit(LoginFailure(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(LoginFailure(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(LoginSuccess(message: message));
    }, failure: (NetworkExceptions error) async {
      emit(LoginFailure(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(LoginSuccess(message: message));
        }
      } catch (e) {
        logger.e(e);
      }
    });
  }

  void rememberPasswordEvent() {
    emit(LoginLoading());
    _isRememberPassword = !_isRememberPassword;
    emit(LoginInitial());
  }

  void validateEmail(String email) {
    emit(LoginInitial());
    errorEmail = checkEmail(email);
    emit(ValidateErrorEmail(errorEmail));
  }

  void validatePhone(String phone) {
    emit(LoginInitial());
    errorPhone = checkPhoneNumber(phone);
    emit(ValidateErrorPhone(errorPhone));
  }

  void validatePass(String pass) {
    emit(LoginInitial());
    errorPass = checkPass(pass);
    emit(ValidateErrorPassword(errorPass));
  }

  void showingKeyboardEvent() {
    emit(LoginLoading());
  }
}
