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/restful_api_client_all_request.dart';
import 'package:mypoint_flutter_app/screen/mobile_card/models/product_mobile_card_model.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../../preference/point/point_manager.dart';
import 'models/usable_voucher_model.dart';

class ProductMobileCardViewModel extends RestfulApiViewModel {
  void Function(String message)? onShowAlertError;
  void Function(UsableVoucherModel data)? onRedeemProductMobileSuccess;

  RxMap<String, List<ProductMobileCardModel>> groupedSection = RxMap<String, List<ProductMobileCardModel>>();
  var mobileCardSections = RxList<ProductMobileCardModel>();
  RxString selectedBrandCode = "".obs;
  List<ProductMobileCardModel> get products {
    return groupedSection[selectedBrandCode.value] ?? [];
  }
  ProductMobileCardModel? selectedProduct;

  int get payPoint {
    return int.tryParse(selectedProduct?.prices?.firstOrNull?.payPoint ?? "0") ?? 0;
  }
  bool get isValidBalance {
    return UserPointManager().point >= (int.tryParse(selectedProduct?.prices?.firstOrNull?.payPoint ?? "0") ?? 0);
  }

  @override
  onInit() {
    super.onInit();
    UserPointManager().fetchUserPoint();
  }

  Future<void> redeemProductMobileCard() async {
    showLoading();
    try {
      final response = await client.redeemMobileCard((selectedProduct?.id ?? 0).toString());
      final itemId = response.data?.itemId ?? "";
      hideLoading();
      if (itemId.isEmpty) {
        print("redeemMobileCard failed: ${response.errorMessage}");
        onShowAlertError?.call(response.errorMessage ?? Constants.commonError);
        return;
      }
      _getMobileCardCode(itemId);
    } catch (error) {
      hideLoading();
      onShowAlertError?.call(error.toString());
      return;
    }
  }

  Future<void> _getMobileCardCode(String itemId) async {
    showLoading();
    try {
      final response = await client.getMobileCardCode(itemId);
      hideLoading();
      final data = response.data?.item;
      if (response.isSuccess && data != null) {
        onRedeemProductMobileSuccess?.call(data);
        return;
      }
      onShowAlertError?.call(response.message ?? Constants.commonError);
    } catch (error) {
      hideLoading();
      onShowAlertError?.call(error.toString());
      return;
    }
  }

  Future<void> getProductMobileCard() async {
    showLoading();
    try {
      final response = await client.productMobileCardGetList();
      final result = response.data?.products ?? [];

      final seen = <String>{};
      final uniqueBrandCode = <ProductMobileCardModel>[];
      for (final p in result) {
        final code = p.brandCode ?? "";
        if (code.isNotEmpty && seen.add(code)) {
          uniqueBrandCode.add(p);
        }
      }
      selectedBrandCode.value = uniqueBrandCode.isNotEmpty ? uniqueBrandCode.first.brandCode ?? "" : "";
      mobileCardSections.value = uniqueBrandCode;

      final Map<String, List<ProductMobileCardModel>> grouped = {};
      for (final product in result) {
        final code = product.brandCode ?? 'unknown';
        if (!grouped.containsKey(code)) {
          grouped[code] = [];
        }
        grouped[code]!.add(product);
      }
      groupedSection.value = grouped;

      hideLoading();
      if (!response.isSuccess) {
        onShowAlertError?.call(response.message ?? Constants.commonError);
      }
    } catch (error) {
      onShowAlertError?.call(error.toString());
    }
  }
}
