import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../../configs/constants.dart';
import 'models/interested_categories_model.dart';

class InterestedCategoriesViewModel extends RestfulApiViewModel {
  var interestedCategories = Rxn<InterestedCategoriesResponse>();
  Set<String> selectedIds = {};

  void Function(String message)? onShowAlertError;

  Future<void> getInterestedCategories() async {
    showLoading();
    try {
      final response = await client.categoryTopLevelGetList();
      hideLoading();
      if (response.isSuccess && response.data != null) {
        final categories = response.data!;
        selectedIds =
            categories.listItems
                ?.where((item) => item.subscribed == "1")
                .map((item) => item.categoryCode ?? '')
                .where((code) => code.isNotEmpty)
                .toList()
                .toSet() ??
            <String>{};
        interestedCategories.value = categories;
      } else {
        onShowAlertError?.call(response.message ?? Constants.commonError);
      }
    } catch (error) {
      hideLoading();
      onShowAlertError?.call(Constants.commonError);
    }
  }

  submitInterestedCategories() async {
    final categories = selectedIds.toList();
    showLoading();
    try {
      final response = await client.submitCategorySubscribe(categories.join(','));
      hideLoading();
      onShowAlertError?.call(
        response.isSuccess ? "Cập nhật sở thích thành công" : response.message ?? Constants.commonError,
      );
      final List<String> categoryCodes =
          interestedCategories.value?.listItems
              ?.map((item) => item.categoryCode ?? '')
              .where((code) => code.isNotEmpty)
              .toList() ??
          [];
      final filteredList = categoryCodes?.where((item) => !categories.contains(item)).toList();
      if (filteredList == null || filteredList.isEmpty) return;
      submitUnsubscribeInterestedCategories(filteredList!);
    } catch (error) {
      hideLoading();
      onShowAlertError?.call(Constants.commonError);
    }
  }

  submitUnsubscribeInterestedCategories(List<String> categories) async {
    final _ = await client.submitCategoryUnsubscribeList(categories.join(','));
  }
}
