import 'package:flutter/cupertino.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/networking/api/product_api.dart' deferred as product_api;
import '../../../networking/restful_api_viewmodel.dart';
import '../../home/models/my_product_model.dart';
import '../../../base/base_response_model.dart';

class MyProductListViewModel extends RestfulApiViewModel {
  final RxInt selectedTabIndex = 0.obs;
  var myProducts = <MyProductModel>[].obs;
  bool _productApiLoaded = false;

  Future<void> _ensureProductApiLoaded() async {
    if (_productApiLoaded) return;
    await product_api.loadLibrary();
    _productApiLoaded = true;
  }

  Future<BaseResponseModel<T>> _callProductApi<T>(Future<BaseResponseModel<T>> Function(dynamic api) fn) async {
    await _ensureProductApiLoaded();
    final api = product_api.ProductApi(client);
    return fn(api);
  }

  @override
  void onInit() {
    super.onInit();
    freshData(isRefresh: true);
  }

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

  Future<void> freshData({bool isRefresh = false}) async {
    final body = {
      "index": isRefresh ? 0 : myProducts.length,
      "size": 20,
      "status": selectedTabIndex.value,
    };
    
    if (isRefresh) {
      showLoading();
    }
    try {
      final response = await _callProductApi((api) => api.getCustomerProducts(body));
      final result = response.data ?? [];
      if (isRefresh) {
        myProducts.assignAll(result);
      } else {
        myProducts.addAll(result);
      }
    } catch (error) {
      if (isRefresh) {
        myProducts.clear();
      }
      debugPrint('Error fetching products: $error');
    } finally {
      if (isRefresh) {
        hideLoading();
      }
    }
  }
}
