import 'dart:async';

import 'package:get/get.dart';
import 'package:rasadyar_core/utils/network/resource.dart';

mixin PaginationControllerMixin<T> on GetxController {
  final Rx<Resource<List<T>>> resource = Resource<List<T>>.initial().obs;
  final RxBool isPaginating = false.obs;
  final RxBool hasMore = true.obs;
  int currentPage = 1;

  Timer? _debounceTimer;
  Future<void> Function()? _lastTriedOperation;

  Future<List<T>> fetchPage(int page);

  void retryLastOperation() => _lastTriedOperation?.call();

  Future<void> refreshData() async {
    _lastTriedOperation = refreshData;
    try {
      currentPage = 1;
      resource.value = const Resource.loading();
      final items = await fetchPage(currentPage);
      if (items.isEmpty) {
        resource.value = const Resource.empty();
        hasMore.value = false;
      } else {
        resource.value = Resource.success(items);
        hasMore.value = true;
      }
    } catch (e) {
      resource.value = Resource.error(e.toString());
    }
  }

  Future<void> loadMoreData() async {
    _lastTriedOperation = loadMoreData;

    if (_debounceTimer?.isActive ?? false) return;

    _debounceTimer = Timer(const Duration(milliseconds: 300), () async {
      if (isPaginating.value || !hasMore.value) return;

      try {
        isPaginating.value = true;
        final nextPage = currentPage + 1;
        final newItems = await fetchPage(nextPage);
        if (newItems.isEmpty) {
          hasMore.value = false;
        } else {
          final currentList = List<T>.from(resource.value.data ?? []);
          currentList.addAll(newItems);
          resource.value = Resource.success(currentList);
          currentPage = nextPage;
        }
      } catch (_) {
        // ignore or optionally handle pagination error
      } finally {
        isPaginating.value = false;
      }
    });
  }
}
