
import 'package:betting/commom/utils/app_utils.dart';
import 'package:betting/view/mobile/favourites_view/widgets/toast_wiget.dart';
import 'package:betting/view/mobile/home_page/home_controller.dart';
import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

import '../../../../data/base_service/api_response.dart';
import '../../../../data/model/res/competitions/competitions.dart';
import '../../../../data/repository/categories/categories_repo.dart';
import '../../../../data/repository/competitions/competitions_repo.dart';

class CompetitionsController extends GetxController {
  RxList favouriteCompetition = <dynamic>[].obs;
  var indexClick = 0.obs;
  var textEditingControllerSearch = TextEditingController();
  var listCompetitionsToCategories = <ItemsCompetitions>[].obs;
  var listCompetitionsFavourites = <ItemsCompetitions>[].obs;
  var listIsFollow = <bool>[].obs;
  var listCompetionsPost = <dynamic>[];
  var listCompetitions = <ItemsCompetitions>[].obs;
  var nameFavourite = "".obs;
  var nameNationFavourites = "".obs;
  var listIdCompetitionsFavourites = <String>[].obs;
  final CategoriesRepo categoriesRepo = CategoriesRepo();
  final CompetitionsRepo competitionsRepo = CompetitionsRepo();
  FToast? fToast;
  var controllerEx = ScrollController();
  var itemLoadMoreEx = <ItemsCompetitions>[].obs;
  var indexPage = 1.obs;
  var competition= Competitions().obs;

  /// variables search competition
  final textSearchController = TextEditingController();
  RxBool isShowClear = false.obs;
  var controllerSearchEx = ScrollController();
  var itemLoadMoreSearchEx = <ItemsCompetitions>[].obs;
  var indexSearchPage = 1.obs;
  var competitionSearch = Competitions().obs;

  @override
  void onInit() {
    getListCompetitions('');
    getListCompetitionsFavorites();
    controllerEx = ScrollController()..addListener(_scrollCompetitions);
    controllerSearchEx = ScrollController()..addListener(_loadMoreSearch);
    super.onInit();
  }

  /// todo: Method refresh data
  void onRefresh() async {
    getListCompetitions('');
    getListCompetitionsFavorites();
    Get.find<HomeController>().onRefreshPressed();

  }

  /// todo: Method get favourite competition list
  getListCompetitionsFavorites() async {
    await competitionsRepo.getListCompetitionsFavorites().then((value) {
      if (value.state == Status.SUCCESS) {
        listCompetitionsFavourites.value = value.object!;
      }
    });
  }

  /// todo: Method get competition list
  getListCompetitions(String? name) async {
    await competitionsRepo.getListCompetitions(0, 20, name).then((value) {
      if (value.state == Status.SUCCESS) {
        listCompetitions.value = value.object!.items!;
      }
    });
  }

  /// todo: Method add competition to favourite list
  addCompetitionsFavorites(List<String> list, ItemsCompetitions? competition) async {
    await competitionsRepo.addCompetitionsFavorites(list).then((value) {
      if (value.state == Status.SUCCESS) {
        listIdCompetitionsFavourites.clear();

        if(competition != null) {
          listCompetitionsFavourites.add(competition);
        }
      }
    },);
  }

  /// todo: Method delete competition from favourite list
  deleteCompetitionsFavorites(String idCompetitionsFavourites) async {
    await competitionsRepo.deleteCompetitionsFavorites(idCompetitionsFavourites).then((value) {
      if (value.state == Status.SUCCESS) {
        listCompetitionsFavourites.removeWhere((element) => element.id == idCompetitionsFavourites);
        var item = listCompetitions.firstWhereOrNull((element) => element.id == idCompetitionsFavourites);

        if(item != null) {
          item.favourite = false;
        }

        listCompetitions.refresh();
        listCompetitionsFavourites.refresh();
      }
    });
  }

  /// todo: method load more competitions
  void _scrollCompetitions(){
    if(controllerEx.position.pixels == controllerEx.position.maxScrollExtent){
      if(itemLoadMoreEx.isNotEmpty){
        indexPage.value ++;
      }
      competitionsRepo.getListCompetitions(indexPage.value, 20, '').then((value) {
        if (value.state == Status.SUCCESS) {
          itemLoadMoreEx.value =[];
          competition.value = value.object!;
          itemLoadMoreEx.value =competition.value.items!;
          listCompetitions.addAll(itemLoadMoreEx);
          listCompetitions.refresh();
          AppUtils.shared.hideLoading();
          Future.delayed(const Duration(seconds: 1), () {
          });
        }
      });
    }
  }

  /// todo: Method load more search competition
  void _loadMoreSearch(){
    if(controllerSearchEx.position.pixels == controllerSearchEx.position.maxScrollExtent){
      if(itemLoadMoreSearchEx.isNotEmpty){
        indexSearchPage.value ++;
      }
      competitionsRepo.getListCompetitions(indexSearchPage.value, 20, textEditingControllerSearch.value.text).then((value) {
        if (value.state == Status.SUCCESS) {
          itemLoadMoreSearchEx.value = [];
          competitionSearch.value = value.object!;
          itemLoadMoreSearchEx.value = competitionSearch.value.items!;
          listCompetitions.addAll(itemLoadMoreSearchEx);
          listCompetitions.refresh();
          AppUtils.shared.hideLoading();
          Future.delayed(const Duration(seconds: 1), () {});
        }
      });
    }
  }

  void addFavourite(BuildContext context, int index) {
    listCompetitions[index].favourite = !listCompetitions[index].favourite!;

    if (listCompetitions[index].favourite == true) {
      listIdCompetitionsFavourites.add(listCompetitions[index].id!);
      addCompetitionsFavorites(listIdCompetitionsFavourites, listCompetitions[index]);
      listCompetitions.refresh();
      listCompetitionsFavourites.refresh();
    } else {
      deleteCompetitionsFavorites(listCompetitions[index].id!);
      listCompetitions.refresh();
      listCompetitionsFavourites.refresh();
    }

    CustomToast().showToast(context, 'Competitions', listCompetitions[index].favourite!);
    update();
  }
}
