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/base_category_request.dart';
import 'package:e_commerce_training/src/model/request/list_product_request.dart';
import 'package:e_commerce_training/src/model/response/base_category_response.dart';
import 'package:e_commerce_training/src/model/response/brand_response.dart';
import 'package:e_commerce_training/src/model/response/home_category_response.dart';
import 'package:e_commerce_training/src/model/response/list_product_response.dart';
import 'package:e_commerce_training/src/model/response/news_response.dart';
import 'package:e_commerce_training/src/model/response/video_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/home/home_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:easy_localization/easy_localization.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class HomeCubit extends Cubit<HomeState> with Validators {
  final AppRepository repository;
  bool isCheck = true;
  List<NewsData> listNews = [];
  List<BrandData> listBrand = [];
  List<VideoData> listVideoHome = [];
  List<ListProductData> listProductData = [];
  List<HomeCategoryData> listHomeCategoryData = [];
  List<BaseCategoryData> listBaseCategoryData = [];
  List<BaseCategoryData> listBaseCategory=[];
  List<ListProductData> listProductResult = [];
  List<ListProductData> listProductCategory = [];
  List<ListProductData> listProductNew = [];
  int selectedIndex = 0;
  int selectedIndex1 = 0;
  int index = 0;
  int idFirst = 0;
  HomeCubit(this.repository) : super(InitialHomeState());

  void refreshHomeEvent() {
    emit(HomeLoading());
    emit(InitialHomeState());
  }

  void isSelected(int index) {
    emit(HomeLoading());
    this.selectedIndex = index;
    emit(InitialHomeState());
  }

  void isSelected2(int index) {
    emit(HomeLoading());
    this.selectedIndex1 = index;
    emit(InitialHomeState());
  }
  void onFilter(int? id) {
    emit(HomeLoading());
    listProductResult.clear();
    for(int i= 0; i < listProductData.length; i++){
      if(listProductData[i].baseCategoryId == id){
        listProductResult.add(listProductData[i]);
      }
    }
    emit(InitialHomeState());
  }
  void onFilterCategory(int? id) {
    emit(HomeLoading());
    listProductCategory.clear();
    for(int i= 0; i < listProductData.length; i++){
      if(listProductData[i].baseCategoryId == id){
        listProductCategory.add(listProductData[i]);
      }
    }
    emit(InitialHomeState());
  }
  void onFilterCategoryNew() {
    emit(HomeLoading());
    listProductNew.clear();
    for(int i= 0; i < listProductData.length; i++){
      listProductNew.addAll(listProductData);
    }
    emit(InitialHomeState());
  }
  void getListVideoHome({bool isRefresh = false, bool isLoadMore = false}) async {
    emit(isRefresh && isLoadMore ? HomeLoading() : InitialHomeState());

    ApiResult<List<VideoData>> listVideo = await repository.getListVideoHome();
    listVideo.when(success: (List<VideoData> data) async {
      listVideoHome = data;
      emit(GetHomeSuccess());
    }, failure: (NetworkExceptions error) async {
      emit(HomeFailure(NetworkExceptions.getErrorMessage(error)));
      try {
        VideoResponse videoResponse = VideoResponse.fromJson(await Util.parseJson("video.json"));
        listVideoHome = videoResponse.data ?? [];
        emit(GetHomeSuccess());
      } catch (e) {
        logger.e(e);
        emit(HomeFailure(R.string.error.tr()));
      }
    });
  }

  void getListNews() async {
    emit(HomeLoading());
    ApiResult<List<NewsData>> newsData = await repository.getNews();
    newsData.when(success: (List<NewsData> data) async {
      listNews = data;
      emit(GetHomeSuccess());
    }, failure: (NetworkExceptions error) async {
      emit(HomeFailure(NetworkExceptions.getErrorMessage(error)));
      try {
        NewsResponse newsResponse = NewsResponse.fromJson(await Util.parseJson("news.json"));
        listNews = newsResponse.data ?? [];
        emit(GetHomeSuccess());
      } catch (e) {
        logger.e(e);
        emit(HomeFailure(R.string.error.tr()));
      }
    });
  }

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

  void getListProduct() async {
    emit(HomeLoading());
    ApiResult<List<ListProductData>> listProductResult = await repository.getListProduct(
      ListProductRequest(
        page: 1,
        pageSize: 100,
      ),
    );
    listProductResult.when(success: (List<ListProductData> data) async {
            listProductData = data;
      emit(GetHomeSuccess());
    }, failure: (NetworkExceptions error) async {
      emit(HomeFailure(NetworkExceptions.getErrorMessage(error)));
      try {
        ListProductResponse listProductResponse =
            ListProductResponse.fromJson(await Util.parseJson("list_product.json"));
                listProductData = listProductResponse.data ?? [];
        emit(GetHomeSuccess());
      } catch (e) {
        logger.e(e);
      }
    });
  }

  void getListBaseCatalog() async {
    emit(HomeLoading());
    //bool isFirstTime = Util.isEmpty(listBaseCategory);
    ApiResult<List<BaseCategoryData>> baseCategory =
    await repository.getListCategory(BaseCategoryRequest());
    baseCategory.when(success: (List<BaseCategoryData> data) async {
      listBaseCategory = data;
     // listBlog = List.filled(listCatalogBlog.length, []);
      emit(GetHomeSuccess());
     // if (isFirstTime) onChangeIndex(0);
    }, failure: (NetworkExceptions error) async {
      emit(HomeFailure(NetworkExceptions.getErrorMessage(error)));
      // Fake get list catalog blog
      try {
        BaseCategoryResponse baseCategoryResponse =
        BaseCategoryResponse.fromJson(await Util.parseJson("base_category.json"));
        listBaseCategory = baseCategoryResponse.data ?? [];
      //  listBlog = List.filled(listCatalogBlog.length, []);
        emit(GetHomeSuccess());
       // if (isFirstTime) onChangeIndex(0);
      } catch (e) {
        logger.e(e);
        emit(HomeFailure(R.string.error.tr()));
      }
    });
  }
  void getHomeCategory() async {
    emit(HomeLoading());
    ApiResult<List<HomeCategoryData>> homeCategoryData = await repository.getListHomeCategory();
    homeCategoryData.when(success: (List<HomeCategoryData> data) async {
      listHomeCategoryData = data;
      emit(GetHomeSuccess());
    }, failure: (NetworkExceptions error) async {
      emit(HomeFailure(NetworkExceptions.getErrorMessage(error)));
      try {
        HomeCategoryResponse homeCategoryResponse =
            HomeCategoryResponse.fromJson(await Util.parseJson("home_category.json"));
        listHomeCategoryData = homeCategoryResponse.data ?? [];
        emit(GetHomeSuccess());
      } catch (e) {
        logger.e(e);
        emit(HomeFailure(R.string.error.tr()));
      }
    });
  }

  void getBaseCategory() async {
    emit(HomeLoading());
    ApiResult<List<BaseCategoryData>> baseCategoryData = await repository.getListCategory(BaseCategoryRequest(
      page: 1,
      pageSize: 100,
      keyword: "",
      isFeature: true,
    ));
    baseCategoryData.when(success: (List<BaseCategoryData> data) async {
      listBaseCategoryData = data;
      onFilter(listProductData.first.baseCategoryId);
      onFilterCategory(listProductData.first.baseCategoryId);
      onFilterCategoryNew();


      emit(GetHomeSuccess());
    }, failure: (NetworkExceptions error) async {
      emit(HomeFailure(NetworkExceptions.getErrorMessage(error)));
      try {
        BaseCategoryResponse baseCategoryResponse = BaseCategoryResponse.fromJson(await Util.parseJson("base_category.json"));
        listBaseCategoryData = baseCategoryResponse.data ?? [];
        onFilter(listProductData.first.baseCategoryId);
        onFilterCategory(listProductData.first.baseCategoryId);
        onFilterCategoryNew();
        emit(GetHomeSuccess());
      } catch (e) {
        logger.e(e);
        emit(HomeFailure(R.string.error.tr()));
      }
    });
  }
}
