import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';


import '../../../core/config/server_response.dart';
import '../../../core/constants/translation_keys.dart';
import '../../../core/data/repositories/app_repositories.dart';
import '../../../core/utils/logs_utils.dart';
import '../../../custom_widgets/custom_toasty.dart';
import '../../../custom_widgets/date_picker.dart';
import '../../../models/UserActivity.dart';
import '../../../models/UserActivityResponseModel.dart';

class UserActivityController extends GetxController {
  RxBool isLoading = true.obs;
  final dateFormat = DateFormat('yyyy-MM-dd');
  late BuildContext context;

  RxString fromDate = "----:--:--".obs;
  RxString toDate = "----:--:--".obs;

  RxList<UserActivity> userActivities = RxList.empty();
  final AppRepositories repository = Get.find<AppRepositories>();

  /// Method for fetch User Activity Data
  void fetchUserActivityData() async {
    ServerResponse userActivityResponse =
        await repository.fetchUserActivity(fromDate.value, toDate.value);
    dp("msg user activity--------show data", userActivityResponse.toString());
    dp("msg user activity--------show data", userActivityResponse.runtimeType);
    UserActivityResponseModel transactionsHistoryResponse =
        UserActivityResponseModel.fromMap(userActivityResponse.response);
    if (userActivityResponse.isError) {
      Toasty.error(
          TranslationKeys.makeTranslation(userActivityResponse.errorMsg));
      isLoading.value = false;
      return;
    }

    userActivities.assignAll(transactionsHistoryResponse.userActivity);
    isLoading.value = false;
    dp("User activity length", userActivities.length);
    dp("User activity length", userActivities.toString());
    update();
    return;
  }

  @override
  Future<void> onInit() async {
    super.onInit();
    fromDate.value =
        dateFormat.format(DateTime.now().subtract(const Duration(days: 30)));
    toDate.value = dateFormat.format(DateTime.now());
    fetchUserActivityData();
  }

  void selectFromDate() async {
    DateTime? fromDateTime = await DatePicker.showDatePicker(context);
    if (fromDateTime != null) {
      fromDate.value = dateFormat.format(fromDateTime);
      toDate.value = "----:--:--";
    }
  }

  void selectToDate() async {
    if (fromDate.value == "----:--:--") {
      Toasty.error(TranslationKeys.makeTranslation(
          TranslationKeys.textSelectFromDateAndProceed));
      return;
    }
    DateTime? toDateTime = await DatePicker.showDatePicker(context);
    if (toDateTime != null) {
      toDate.value = dateFormat.format(toDateTime);
      fetchUserActivityData();
    }
  }
}
