import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/configs/constants.dart';
import 'package:mypoint_flutter_app/networking/api/product_api.dart' deferred as product_api;
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import 'package:mypoint_flutter_app/screen/traffic_service/traffic_service_model.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../../base/base_response_model.dart';

class TrafficServiceViewModel extends RestfulApiViewModel {
  var trafficData = Rxn<TrafficServiceResponseModel>();
  void Function(String message)? onShowAlertError;
  var trafficServiceDetail = Rxn<TrafficServiceDetailModel>();
  RxInt selectedIndex = 0.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);
  }

  List<HeaderFilterOrderModel> get headerFilterOrder {
    return [
      HeaderFilterOrderModel(
        title: 'Tất cả',
        suffixChecking: 'tatca',
        selected: true,
      ),
      HeaderFilterOrderModel(
        title: 'Hiệu lực',
        suffixChecking: 'hieuluc',
      ),
      HeaderFilterOrderModel(
        title: 'Không hiệu lực',
        expired: "true",
        suffixChecking: 'khonghieuluc',
      ),
    ];
  }

  Future<void> getTrafficServiceData() async {
    var body = headerFilterOrder[selectedIndex.value].params;
    body['page'] = 1;
    body['size'] = 10000;
    showLoading();
    try {
      final response = await _callProductApi((api) => api.getProductVnTraSold(body));
      hideLoading();
      if (response.isSuccess) {
        trafficData.value = response.data;
      } else {
        onShowAlertError?.call(response.errorMessage ?? Constants.commonError);
      }
    } catch (error) {
      hideLoading();
      onShowAlertError?.call("Error fetching product detail: $error");
    }
  }

  Future<void> getTrafficServiceDetail(String id) async {
    showLoading();
    try {
      final response = await client.getDetailMyPackageVnTra(id);
      hideLoading();
      if (response.isSuccess) {
        trafficServiceDetail.value = response.data;
      } else {
        onShowAlertError?.call(response.errorMessage ?? Constants.commonError);
      }
    } catch (error) {
      hideLoading();
      onShowAlertError?.call("Error fetching product detail: $error");
    }
  }
}
