import 'package:bloc/bloc.dart';
import 'package:e_commerce_training/res/R.dart';
import 'package:e_commerce_training/src/model/repository/app_repository.dart';
import 'package:e_commerce_training/src/model/request/filter_request.dart';
import 'package:e_commerce_training/src/model/response/brand_response.dart';
import 'package:e_commerce_training/src/model/response/detail_category_response.dart';
import 'package:e_commerce_training/src/model/response/filter_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/util/logger.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:equatable/equatable.dart';
import 'package:easy_localization/easy_localization.dart';

part 'detail_category_state.dart';

class RowDetailCategoryCubit extends Cubit<RowDetailCategoryState> {
  final AppRepository repository;

  RowDetailCategoryCubit(this.repository) : super(DetailCategoryInitial());
  DetailCategoryData? detailCategoryData;
  List<BrandData> listBrand = [];
  List<FilterData> listFilter = [];
  List<FilterData> listAllFilter = [];
  int index = 0;
  bool isCheck = true;
  List<int> positionManufacturer = [];
  List<int> positionPrice = [];
  List<int> cleanAll = [];

  void setCheck() {
    emit(DetailCategoryLoading());
    this.isCheck = !isCheck;
    emit(DetailCategoryInitial());
  }

  void onChangeManufacturer(int itemIndex) {
    emit(DetailCategoryLoading());
    // listAllFilter.clear();
    if (this.positionManufacturer.contains(itemIndex)) {
      this.positionManufacturer.remove(itemIndex);
    } else {
      this.positionManufacturer.add(itemIndex);
    }
    // if (this.positionManufacturer.isNotEmpty) {
    //   for (int i = 0; i < positionManufacturer.length; i++) {
    //     if (listFilter[i].filterId == filterId) {
    //       listAllFilter.add(listFilter[i]);
    //     }
    //   }
    // }
    emit(DetailCategoryInitial());
  }

  void onFilter(int? filterId) {
    emit(DetailCategoryLoading());
    for (int i = 0; i < listFilter.length; i++) {
      if (listFilter[i].filterId == filterId) {
        listAllFilter.add(listFilter[i]);
      }
    }
    emit(DetailCategoryInitial());
  }

  void onChangePrice(int itemIndex) {
    emit(DetailCategoryLoading());
    if (this.positionPrice.contains(itemIndex)) {
      this.positionPrice.remove(itemIndex);
    } else {
      this.positionPrice.add(itemIndex);
    }
    emit(DetailCategoryInitial());
  }

  void cleanDataAll() {
    emit(DetailCategoryLoading());
    positionManufacturer.clear();
    positionPrice.clear();
    emit(DetailCategoryInitial());
  }

  void getListBrand() async {
    emit(DetailCategoryLoading());
    ApiResult<List<BrandData>> brandData = await repository.getListBrand();
    brandData.when(success: (List<BrandData> data) async {
      listBrand = data;
      emit(GetDetailCategorySuccess());
    }, failure: (NetworkExceptions error) async {
      emit(DetailCategoryFailure(NetworkExceptions.getErrorMessage(error)));
      try {
        BrandResponse brandResponse = BrandResponse.fromJson(await Util.parseJson("branch.json"));
        listBrand = brandResponse.data ?? [];
        emit(GetDetailCategorySuccess());
      } catch (e) {
        logger.e(e);
        emit(DetailCategoryFailure(R.string.error.tr()));
      }
    });
  }

  void getListDetailCategory({bool isRefresh = false, bool isLoadMore = false, int? id}) async {
    emit(!isRefresh && !isLoadMore ? DetailCategoryLoading() : DetailCategoryInitial());
    ApiResult<DetailCategoryData> detailCategoryResult = await repository.getDetailCategory(id!);
    detailCategoryResult.when(success: (DetailCategoryData data) async {
      detailCategoryData = data;
      //queryItem(detailCategoryData?.id);
      emit(GetDetailCategorySuccess());
    }, failure: (NetworkExceptions error) async {
      emit(DetailCategoryFailure(NetworkExceptions.getErrorMessage(error)));
      try {
        DetailCategoryResponse detailCategoryResponse = DetailCategoryResponse.fromJson(await Util.parseJson("detail_category.json"));
        detailCategoryData = detailCategoryResponse.detailCategoryData;
        // queryItem(detailCategoryData?.id);
        emit(GetDetailCategorySuccess());
      } catch (e) {
        logger.e(e);
        emit(DetailCategoryFailure(R.string.error.tr()));
      }
    });
  }

  void getListFilter() async {
    emit(DetailCategoryLoading());
    ApiResult<List<FilterData>> filterResult = await repository.getListFilter(
      FilterRequest(
        filterId: 1,
        brandId: 1,
      ),
    );
    filterResult.when(success: (List<FilterData> data) async {
      listFilter = data;
      onFilter(listFilter.first.filterId);
      emit(GetDetailCategorySuccess());
    }, failure: (NetworkExceptions error) async {
      emit(DetailCategoryFailure(NetworkExceptions.getErrorMessage(error)));
      try {
        FilterResponse filterResponse = FilterResponse.fromJson(await Util.parseJson("filter.json"));
        listFilter = filterResponse.data ?? [];
        onFilter(listFilter.first.filterId);
        emit(GetDetailCategorySuccess());
      } catch (e) {
        logger.e(e);
        emit(DetailCategoryFailure(R.string.error.tr()));
      }
    });
  }
}
