import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/extensions/datetime_extensions.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../networking/restful_api_viewmodel.dart';
import 'history/transaction_category_model.dart';
import 'history/transaction_history_response_model.dart';

class TransactionsHistoryViewModel extends RestfulApiViewModel {
  var categories = RxList<TransactionCategoryModel>();
  var historyResponse = Rxn<TransactionHistoryResponse>();
  void Function(String message)? onShowAlertError;
  TransactionCategoryModel? categorySelected;
  DateTime date = DateTime.now();
  bool _isLoading = false;

  @override
  onInit() {
    super.onInit();
    _getCategories();
  }

  Future<void> _getCategories() async {
    showLoading();
    try {
      final response = await client.getTransactionHistoryCategories();
      categories.value = response.data ?? [];
      categorySelected = categories.isNotEmpty ? categories.first : null;
      hideLoading();
      getTransactionHistoryResponse();
    } catch (error) {
      hideLoading();
      onShowAlertError?.call("Error fetching product detail: $error");
    }
  }

  Future<void> getTransactionHistoryResponse() async {
    if (_isLoading) return;
    final body = {
      'category_code': categorySelected?.code ?? '',
      'date': date.toFormattedString(format: 'yyyy-MM'),
      'limit': 10000,
      'offset':0,
    };
    _isLoading = true;
    showLoading();
    try {
      final response = await client.getTransactionHistoryResponse(body);
      final data = response.data;
      historyResponse.value = data;
      _isLoading = false;
      hideLoading();
    } catch (error) {
      _isLoading = false;
      hideLoading();
      onShowAlertError?.call("Error fetching product detail: $error");
    }
  }
}
