import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/extensions/collection_extension.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';

import '../../networking/restful_api_viewmodel.dart';
import 'models/history_point_cashback_model.dart';

class HistoryPointCashBackViewModel extends RestfulApiViewModel {
  late List<CashBackPointOrderStatus> tagStatus;
  CashBackPointOrderStatus get selectedTag {
    return tagStatus.safe(selectedTabIndex.value) ?? CashBackPointOrderStatus.pending;
  }

  final RxInt selectedTabIndex = 0.obs;
  var pointCashBackData = Rxn<HistoryPointCashBackResponse>();
  List<HistoryPointCashBackOrderModel> get orders {
    return pointCashBackData.value?.orders ?? [];
  }

  int _page = 1;

  @override
  void onInit() {
    super.onInit();
    tagStatus = [
      CashBackPointOrderStatus.pending,
      CashBackPointOrderStatus.approved,
      CashBackPointOrderStatus.confirmed,
      CashBackPointOrderStatus.reject,
    ];
    freshData(isRefresh: true);
  }

  void freshData({bool isRefresh = false}) {
    if (isRefresh) {
      _page = 1;
    } else {
      _page += 1;
    }
    final body = {"page": _page, "size": 20, "type": selectedTag.rawValue};
    client
        .historyPointCashBackRequest(body)
        .then((response) {
          final result = response.data;
          if (isRefresh) {
            pointCashBackData.value = result;
          } else {
            final orders = result?.orders ?? [];
            pointCashBackData.value?.orders?.addAll(orders);
            pointCashBackData.refresh();
          }
        })
        .catchError((error) {
          print('Error fetching products: $error');
        });
  }

  void selectTab(int index) {
    selectedTabIndex.value = index;
    freshData(isRefresh: true);
  }
}
