import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../../preference/data_preference.dart';
import 'models/category_notify_item_model.dart';
import 'models/notification_item_model.dart';
import 'notification_detail_screen.dart';

class NotificationViewModel extends RestfulApiViewModel {
  var categories = RxList<CategoryNotifyItemModel>();
  var notifications = RxList<NotificationItemModel>();
  final RxBool isLoading = false.obs;
  final _pageLimit = 10;
  var _notificationIndex = 0;
  void Function(String message)? onShowAlertError;
  var _hasMoreData = true;

  CategoryNotifyItemModel? get selectedCategory =>
      categories.isNotEmpty ? categories.firstWhere((item) => item.isSelected ?? false) : null;
  
  @override
  void onInit() {
    super.onInit();
    _fetchCategories();
  }

  void _fetchCategories() async {
    showLoading();
    client.getNotificationCategories().then((value) {
      final results = value.data ?? [];
      if (results.isNotEmpty) {
        results[0].isSelected = true;
      }
      categories.value = results;
      fetchNotifications(refresh: true);
    });
  }

  void fetchNotifications({bool refresh = false}) async {
    if (isLoading.value) return;
    if (!refresh && !_hasMoreData) { return; }
    if (refresh) {
      _notificationIndex = 0;
    }
    isLoading.value = true;
    String? token = DataPreference.instance.token ?? "";
    final body = {
      "access_token": token,
      "start": _notificationIndex,
      "limit": _pageLimit,
      "noti_group_id": selectedCategory?.id ?? "",
    };
    client.getNotifications(body).then((value) {
      isLoading.value = false;
      hideLoading();
      final items = value.data?.items ?? [];
      if (refresh) {
        notifications.value = items;
      } else {
        notifications.addAll(items);
      }
      _notificationIndex += items.length;
      _hasMoreData = (value.data?.items?.length ?? 0) == _pageLimit;
    });
  }

  void selectCategory(int index) {
    for (var i = 0; i < categories.length; i++) {
      categories[i].isSelected = i == index;
    }
    fetchNotifications(refresh: true);
  }

  void notificationMarkAsSeen() {
    client.notificationMarkAsSeen().then((value) {
      _fetchCategories();
    });
  }

  void deleteAllNotifications() {
    client.deleteAllNotifications().then((value) {
      _fetchCategories();
    });
  }

  void handleRemoveNotification(NotificationItemModel item) {
    if (item.notificationId == null) { return; }
    client.deleteNotification(item.notificationId ?? "").then((value) {
      notifications.remove(item);
      if (notifications.length <= _pageLimit) {
        fetchNotifications(refresh: false);
      }
    });
  }

  void handleClickNotification(NotificationItemModel item) {
    showLoading();
    client.getNotificationDetail(item.notificationId ?? "").then((value) {
      hideLoading();
      if (!value.isSuccess) return;
      final notification = value.data?.notification;
      if (notification == null) return;
      final pushSuccess = notification.directionalScreen?.begin() ?? false;
      if (!pushSuccess) {
        Get.to(() => NotificationDetailScreen(notification: notification));
      }
    });
  }
}
