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/list_product_request.dart';
import 'package:e_commerce_training/src/model/response/list_product_response.dart';
import 'package:e_commerce_training/src/model/response/product_suggest.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/search/search_state.dart';
import 'package:e_commerce_training/src/util/logger.dart';
import 'package:e_commerce_training/src/util/util.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:easy_localization/easy_localization.dart';

class SearchCubit extends Cubit<SearchState> {
  final AppRepository repository;
  List<KeywordSuggestData> listSuggest = [];
  List<ListProductData> listProduct = [];
  List<ListProductData> searchListProduct = [];
  int _currentPage = 1;

  int get currentPage => _currentPage;

  SearchCubit(this.repository) : super(SearchInitial());

  void getSuggestSearch({bool isRefresh = false, bool isLoadMore = false}) {
    emit((!isRefresh && !isLoadMore) ? SearchLoading() : SearchInitial());
    if (isRefresh) _currentPage = 1;
    if (isLoadMore) {
      _currentPage++;
    }
  }

  void searchKeywordEvent(String text) {
    emit(SearchLoading());
    listProductSuggest();
    emit(SearchSuccess());
  }

  void listProductSuggest() async {
    emit(SearchLoading());
    ApiResult<List<KeywordSuggestData>> listVideo = await repository.getListKeywordSuggest();
    listVideo.when(success: (List<KeywordSuggestData> data) async {
      listSuggest = data;
      emit(SearchSuccess());
    }, failure: (NetworkExceptions error) async {
      emit(SearchFailure(NetworkExceptions.getErrorMessage(error)));
      try {
        KeywordSuggestResponse response = KeywordSuggestResponse.fromJson(await Util.parseJson("product_suggest.json"));
        listSuggest = response.data ?? [];
        emit(SearchSuccess());
      } catch (e) {
        logger.e(e);
        emit(SearchFailure(R.string.error.tr()));
      }
    });
  }

  void searchByKeyboard(String keyword) async {
    emit(SearchInitial());
    if (Util.isEmpty(keyword)) {
      listProduct.clear();
      emit(SearchSuccess());
    } else {
      ApiResult<List<ListProductData>> listProductResult = await repository.getListProduct(
        ListProductRequest(
          keyword: keyword,
        ),
      );
      listProductResult.when(success: (List<ListProductData> data) async {
        listProduct = data;
        if (keyword.length > 0) {
          Set<ListProductData> search = Set.from(listProduct);
          searchListProduct.clear();
          search.forEach(
            (element) {
              if (element.vietnameseName!.toLowerCase().contains(keyword) || element.vietnameseName!.contains(keyword)) {
                searchListProduct.add(element);
              }
            },
          );
        }
        emit(SearchSuccess());
      }, failure: (NetworkExceptions error) async {
        emit(SearchFailure(NetworkExceptions.getErrorMessage(error)));
        try {
          ListProductResponse listProductResponse = ListProductResponse.fromJson(await Util.parseJson("list_product.json"));
          listProduct = listProductResponse.data ?? [];
          if (keyword.length > 0) {
            Set<ListProductData> search = Set.from(listProduct);
            searchListProduct.clear();
            search.forEach(
              (element) {
                if (element.vietnameseName!.toLowerCase().contains(keyword) || element.vietnameseName!.contains(keyword)) {
                  searchListProduct.add(element);
                }
              },
            );
          }
          emit(SearchSuccess());
        } catch (e) {
          logger.e(e);
        }
      });
    }
  }

  void search(String? key) {
    for (int i = 0; i < listProduct.length; i++) {
      if (listProduct[i].vietnameseName!.contains(key!)) {
        searchListProduct.add(listProduct[i]);
      }
    }
  }
}
