import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/core/network/restful_api_client_all_request.dart';
import '../../core/network/restful_api_viewmodel.dart';
import '../../shared/preferences/point/point_manager.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 _userClickDailyCheckIn = false;

  bool get todayIsChecked {
    if (_userClickDailyCheckIn) return true;
    final counter = checkInData.value?.dailyCounter;
    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, _) {
        UserPointManager().fetchUserPoint();
        _userClickDailyCheckIn = true;
        submitData.value = data;
        submitDataResponse?.call(data);
        _rewardOpportunityGetList(); // Refresh data after successful check-in
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg, false);
      },
    );
  }
}