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

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

  void Function(String message)? onShowAlertError;

  Future<void> getInterestedCategories() async {
    await callApi<InterestedCategoriesResponse>(
      request: () => client.categoryTopLevelGetList(),
      onSuccess: (data, _) {
        selectedIds =
            data.listItems
                ?.where((item) => item.subscribed == "1")
                .map((item) => item.categoryCode ?? '')
                .where((code) => code.isNotEmpty)
                .toList()
                .toSet() ??
            <String>{};
        interestedCategories.value = data;
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg);
      },
    );
  }

  Future<void> submitInterestedCategories() async {
    final categories = selectedIds.toList();
    await callApi<EmptyCodable>(
      request: () => client.submitCategorySubscribe(categories.join(',')),
      onSuccess: (data, _) {
        onShowAlertError?.call("Cập nhật sở thích thành công");
        _handleUnsubscribeCategories(categories);
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg);
      },
    );
  }

  void _handleUnsubscribeCategories(List<String> categories) {
    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.isNotEmpty) {
      submitUnsubscribeInterestedCategories(filteredList);
    }
  }

  Future<void> submitUnsubscribeInterestedCategories(List<String> categories) async {
    await callApi<EmptyCodable>(
      request: () => client.submitCategoryUnsubscribeList(categories.join(',')),
      onSuccess: (data, _) {
        // Silent success for unsubscribe
      },
      onFailure: (msg, _, _) async {
        // Silent failure for unsubscribe
      },
    );
  }
}
