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/response/city_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/register_member_ship/register_member_ship_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';

class RegisterMemberShipCubit extends Cubit<RegisterMemberShipState> with Validators {
  final AppRepository repository;
  String? errorName;
  String? errorAddress;
  String? errorEmail;

  String get token => appPreference.getData(Const.TOKEN) ?? "";

  String get fullName => appPreference.getData(Const.FULL_NAME) ?? "";

  String get email => appPreference.getData(Const.EMAIL) ?? "";

  String get shippingCityName => appPreference.getData(Const.CITY_NAME) ?? "";

  int get shippingCityId => appPreference.getIntData(Const.CITY_ID) ?? -1;

  CityData? selectedCity;
  List<CityData> listCity = [];

  RegisterMemberShipCubit(this.repository) : super(RegisterMemberShipInitial());

  void validateName(String name) {
    emit(RegisterMemberShipInitial());
    errorName = checkName(name)!;
    emit(RegisterMemberShipFailure(errorName));
  }

  void validateEmail(String email) {
    emit(RegisterMemberShipInitial());
    errorEmail = checkEmail(email)!;
    emit(RegisterMemberShipFailure(errorEmail));
  }

  void getCity() async {
    ApiResult<CityResponse> apiResult = await repository.getListCity();
    apiResult.when(success: (CityResponse data) async {
      listCity = data.data ?? [];
      if (shippingCityId is int && shippingCityId >= 0) {
        try {
          selectedCity = listCity.firstWhere((element) => element.cityId == shippingCityId);
        } catch (e) {}
      }
    }, failure: (NetworkExceptions error) async {
      emit(RegisterMemberShipFailure(NetworkExceptions.getErrorMessage(error)));
      // Fake get city response
      try {
        CityResponse data = CityResponse.fromJson(await Util.parseJson("city.json"));
        listCity = data.data ?? [];
        if (shippingCityId is int && shippingCityId >= 0) {
          if (shippingCityId is int && shippingCityId >= 0) {
            try {
              selectedCity = listCity.firstWhere((element) => element.cityId == shippingCityId);
            } catch (e) {}
          }
        }
      } catch (e) {
        logger.e(e);
      }
    });
  }

  void selectCity(CityData? city) {
    this.selectedCity = city;
    appPreference.setData(Const.CITY_ID, city?.cityId);
    appPreference.setData(Const.CITY_NAME, city?.cityName);
  }

  List<CityData> searchCity(String? name) {
    if (Util.isEmpty(name)) return listCity;
    return listCity
        .where(
          (e) => Util.convertVNtoText(e.cityName ?? "").contains(
            Util.convertVNtoText(name!),
          ),
        )
        .toList();
  }
}
