import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/networking/restful_api_request.dart';
import '../../base/restful_api_viewmodel.dart';
import 'model/affiliate_brand_model.dart';
import 'model/affiliate_category_model.dart';
import 'model/affiliate_category_type.dart';
import 'model/affiliate_product_top_sale_model.dart';
import 'model/cashback_overview_model.dart';

class AffiliateTabViewModel extends RestfulApiViewModel {
  final RxList<AffiliateBrandModel> affiliateBrands = <AffiliateBrandModel>[].obs;
  final RxList<AffiliateCategoryModel> affiliateCategories = <AffiliateCategoryModel>[].obs;
  final RxList<AffiliateProductTopSaleModel> affiliateProducts = <AffiliateProductTopSaleModel>[].obs;
  final RxBool isLoading = false.obs;
  var overview = Rxn<CashbackOverviewModel>();

  @override
  void onInit() {
    super.onInit();
    refreshData();
    _getAffiliateOverview();
  }

  Future<void> refreshData() async {
    isLoading.value = true;
    await Future.wait([
      _getAffiliateBrandGetList(),
      _getAffiliateCategoryGetList(),
      _getAffiliateProductTopSale(),
    ]);
    isLoading.value = false;
  }

  Future<void> _getAffiliateBrandGetList() async {
    try {
      final result = await client.affiliateBrandGetList();
      affiliateBrands.value = (result.data ?? []).take(6).toList();
    } catch (error) {
      print("Error fetching affiliate brands: $error");
    }
  }

  Future<void> _getAffiliateCategoryGetList() async {
    try {
      final result = await client.affiliateCategoryGetList();
      final category = AffiliateCategoryModel(
        code: AffiliateCategoryType.other,
        name: "Khác",
      );
      final data = (result.data ?? []).take(7).toList();
      data.add(category);
      affiliateCategories.value = data;
    } catch (error) {
      print("Error fetching affiliate brands: $error");
    }
  }

  Future<void> _getAffiliateProductTopSale() async {
    try {
      final result = await client.affiliateProductTopSale();
      affiliateProducts.value = result.data ?? [];
    } catch (error) {
      print("Error fetching affiliate brands: $error");
    }
  }

  Future<void> _getAffiliateOverview() async {
    try {
      final result = await client.getCashBackOverview();
      overview.value = result.data;
    } catch (error) {
      print("Error fetching affiliate brands: $error");
    }
  }
}