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 'daily_checkin_models.dart';

class DailyCheckInViewModel extends RestfulApiViewModel {
  final Rxn<CheckInDataModel> checkInData = Rxn<CheckInDataModel>();
  final Rxn<SubmitCheckInData> submitData = Rxn<SubmitCheckInData>();
  void Function(String message, bool onBack)? onShowAlertError;
  void Function(SubmitCheckInData? data)? submitDataResponse;

  bool get todayIsChecked {
    final counter = checkInData.value?.counters?.first;
    final items = counter?.values ?? [];
    return (items.firstOrNull?.counterValue ?? '') == '1';
  }

  @override
  void onInit() {
    super.onInit();
    _rewardOpportunityGetList();
  }

  Future<void> _rewardOpportunityGetList() async {
    await callApi<CheckInDataModel>(
      request: () => client.rewardOpportunityGetList(),
      onSuccess: (data, _) {
        checkInData.value = data;
      },
      onFailure: (msg, _, __) async {
        onShowAlertError?.call(msg, true);
      },
    );
  }

  Future<void> submitCheckIn() async {
    await callApi<SubmitCheckInData>(
      request: () => client.submitCheckIn(),
      onSuccess: (data, _) {
        submitData.value = data;
        submitDataResponse?.call(data);
        _rewardOpportunityGetList(); // Refresh data after successful check-in
      },
      onFailure: (msg, _, __) async {
        onShowAlertError?.call(msg, false);
      },
    );
  }
}