import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/extensions/num_extension.dart';
import 'package:mypoint_flutter_app/networking/api/product_api.dart' deferred as product_api;
import '../../../configs/constants.dart';
import '../../../networking/restful_api_viewmodel.dart';
import '../../mobile_card/models/usable_voucher_model.dart';
import '../../../base/base_response_model.dart';

class MyMobileCardDetailViewModel extends RestfulApiViewModel {
  String itemId;
  var dataCard = Rxn<UsableVoucherModel>();
  void Function(String message)? onShowAlertError;

  MyMobileCardDetailViewModel({required this.itemId});
  RxBool isUsed = true.obs;
  String get brandName => dataCard.value?.brand?.brandName ?? dataCard.value?.voucherTypeName ?? '';
  String get code => dataCard.value?.codeSecret ?? '';
  String get serial => dataCard.value?.serial ?? '';
  String get valueText => (int.tryParse(dataCard.value?.prices?.firstOrNull?.originalPrice ?? '') ?? 0).money(CurrencyUnit.vnd);
  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);
  }

  Future<void> getMobileCardDetail() async {
    showLoading();
    try {
      final response = await _callProductApi((api) => api.getMobileCardCode(itemId));
      final data = response.data?.item;
      if (response.isSuccess && data != null) {
        dataCard.value = data;
        isUsed.value = makeUsedCardDetail();
        return;
      }
      onShowAlertError?.call(response.message ?? Constants.commonError);
    } catch (error) {
      onShowAlertError?.call(Constants.commonError);
    } finally {
      hideLoading();
    }
  }

  bool makeUsedCardDetail() {
    final s = (dataCard.value?.statusCode ?? '').toUpperCase();
    if (s == 'USED' || s == 'CONSUMED') return true;
    final t = (dataCard.value?.status ?? '').toLowerCase();
    return t.contains('đã sử dụng') || t.contains('used');
  }

  Future<void> onChangeCardStatus() async {
    final newState = !isUsed.value;
    showLoading();
    try {
      final response =
          newState
              ? await _callProductApi((api) => api.myProductMarkAsUsed(itemId))
              : await _callProductApi((api) => api.myProductMarkAsNotUsedYet(itemId));
      if (response.isSuccess) {
        isUsed.value = newState;
      }
    } catch (_) {
      onShowAlertError?.call(Constants.commonError);
    } finally {
      hideLoading();
    }
  }
}
