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/restful_api_client_all_request.dart';
import '../../../configs/constants.dart';
import '../../../networking/restful_api_viewmodel.dart';
import '../../mobile_card/models/usable_voucher_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);

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

  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 client.myProductMarkAsUsed(itemId) : await client.myProductMarkAsNotUsedYet(itemId);
      if (response.isSuccess) {
        isUsed.value = newState;
      }
    } catch (_) {

    } finally {
      hideLoading();
    }
  }
}