import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/collection_extension.dart';
import 'package:mypoint_flutter_app/core/network/restful_api_client_all_request.dart';
import '../../core/network/restful_api_viewmodel.dart';
import 'models/history_point_cashback_model.dart';

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

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

  int _page = 1;

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

  Future<void> freshData({bool isRefresh = false}) async {
    _page = isRefresh ? 1 : _page + 1;
    final body = {"page": _page, "size": 20, "type": selectedTag.rawValue};
    await callApi<HistoryPointCashBackResponse>(
      request: () => client.historyPointCashBackRequest(body),
      onSuccess: (data, _) {
        if (isRefresh) {
          pointCashBackData.value = data;
        } else {
          final next = data.orders ?? [];
          pointCashBackData.value?.orders?.addAll(next);
          pointCashBackData.refresh();
        }
      },
      onFailure: (_, _, _) async {},
      withLoading: isRefresh,
    );
  }

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