import 'package:betting/data/base_service/api_response.dart';
import 'package:betting/data/model/res/teams/teams.dart';
import 'package:betting/data/repository/teams/team_repo.dart';
import 'package:betting/view/mobile/favourites_view/bottom_sheet_widget/bottom_sheet_widget.dart';
import 'package:betting/view/mobile/favourites_view/teams/switch_controller.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:flutter/material.dart';
import 'package:get/get.dart';

class TeamsScreenController extends GetxController {
  final _teamRepo = TeamsRepo();

  /// List teams
  RxList teams = <ItemTeams>[].obs;
  RxList favouriteTeams = <ItemTeams>[].obs;

  RxList favourites = <ItemTeams>[].obs;
  RxList listNotifyMatch = <bool>[].obs;
  RxList listNotifyNews = <bool>[].obs;
  RxBool isFavourite = true.obs;
  var controllerEx = ScrollController();
  var teamList = Teams().obs;
  var itemLoadMoreEx = <ItemTeams>[].obs;
  var indexPage = 1.obs;

  /// variables for search dialog
  RxBool isShowClear = false.obs;
  final textSearchController = TextEditingController();
  var controllerSearchScroll = ScrollController();
  var teamSearch = Teams().obs;
  var itemLoadMoreSearch = <ItemTeams>[].obs;
  var pageIndex = 1.obs;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    getListTeam('');
    getFavouriteTeams();
    controllerEx = ScrollController()..addListener(_scrollTeams);
    controllerSearchScroll = ScrollController()..addListener(_loadMoreSearch);
  }

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

  }

  /// todo: Method get teams
  void getListTeam(String? name) async{
    await _teamRepo.getListTeam(0, 20, name).then((value) async {
      if(value.state == Status.SUCCESS) {
        teams.value = value.object!.items!;
      }
    });
  }

  /// todo: Method add team to list favourite
  void addFavourite(List<ItemTeams> favourites, List listNotifyMatch, List listNotifyNews, ItemTeams item) async {
    await _teamRepo.addTeamFollow(favourites, listNotifyMatch, listNotifyNews).then((value) {
      if(value.state == Status.SUCCESS) {
        print('add team to favourite list successfully!');
        favouriteTeams.add(item);
      } else {
        print('add team to favourite list failed!');
      }
    });
  }

  /// todo: Method get list favourite team
  void getFavouriteTeams() async{
    await _teamRepo.getFavouriteTeams().then((value) {
      if(value.state == Status.SUCCESS) {
        favouriteTeams.value = value.object!;
      }
    });
  }

  /// todo: delete favourite team
  void deleteFavouriteTeam(String id) async{
    await _teamRepo.delFavouriteTeam(id).then((value) {
      if(value.state == Status.SUCCESS) {
        print('Delete success!');
        favouriteTeams.removeWhere((element) => element.id == id);
      } else {
        print('Delete failed!');
      }
    });
  }

  /// todo: add team to favourite list
  void addFavouriteTeam(BuildContext context, int index, SwitchController switchController) {
    teams[index].favourite = !teams[index].favourite;
    isFavourite.value = teams[index].favourite;

    if (teams[index].favourite == true) {
      favourites.add(teams[index]);
      listNotifyMatch.add(switchController.isMatchAlert.value);
      listNotifyNews.add(switchController.isTeamNews.value);

      addFavourite(favourites as List<ItemTeams>,
          listNotifyMatch,
          listNotifyNews, teams[index]);
      showModalBottomSheet(
        backgroundColor: Colors.transparent,
        context: context,
        builder: (BuildContext context) {
          return BottomSheetWidget();
        },
      ).whenComplete(() {
        CustomToast().showToast(context, 'Team', isFavourite.value);
      });
    } else {
      deleteFavouriteTeam(teams[index].id);
      CustomToast().showToast(context, 'Team', teams[index].favourite);
    }

    teams.refresh();
    favouriteTeams.refresh();
    update();
  }

  /// todo: load more
  void _scrollTeams(){
    if(controllerEx.position.pixels == controllerEx.position.maxScrollExtent){
      if(itemLoadMoreEx.isNotEmpty){
        indexPage.value++;
      }

      _teamRepo.getListTeam(indexPage.value, 20, '').then((value) {
        if (value.state == Status.SUCCESS) {
          itemLoadMoreEx.value =[];
          teamList.value = value.object!;
          itemLoadMoreEx.value = teamList.value.items!;
          teams.addAll(itemLoadMoreEx);
          teams.refresh();
          Future.delayed(const Duration(seconds: 1), () {
          });
        }
      });
    }
  }

  /// todo: load more search
  void _loadMoreSearch(){
    if(controllerSearchScroll.position.pixels == controllerSearchScroll.position.maxScrollExtent){
      if(itemLoadMoreSearch.isNotEmpty){
        pageIndex.value++;
      }

      _teamRepo.getListTeam(pageIndex.value, 20,textSearchController.value.text).then((value) {
        if (value.state == Status.SUCCESS) {
          itemLoadMoreSearch.value =[];
          teamSearch.value = value.object!;
          itemLoadMoreSearch.value = teamSearch.value.items!;
          teams.addAll(itemLoadMoreSearch);
          teams.refresh();
          Future.delayed(const Duration(seconds: 1), () {
          });
        }
      });
    }
  }
}
