import 'dart:convert';
import 'package:get/get.dart';
import '../../constant/links.dart';
import '../functions/crud.dart';

class DriverDocsController extends GetxController {
  var pendingDrivers = [].obs;
  var isLoading = false.obs;
  var isMoreLoading = false.obs;
  var hasMore = true.obs;
  int _offset = 0;
  final int _limit = 10;
  final CRUD _crud = CRUD();

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

  Future<void> getPendingDrivers({bool refresh = true}) async {
    if (refresh) {
      isLoading.value = true;
      _offset = 0;
      hasMore.value = true;
    } else {
      if (isMoreLoading.value || !hasMore.value) return;
      isMoreLoading.value = true;
    }

    try {
      var response = await _crud.post(
        link: AppLink.getDriversPending,
        payload: {"limit": _limit.toString(), "offset": _offset.toString()},
      );
      if (response != null && response != 'failure' && response != 'token_expired') {
        var decoded = response is String ? jsonDecode(response) : response;
        if (decoded['status'] == "success") {
          List newItems = decoded['message'] ?? [];
          if (refresh) {
            pendingDrivers.assignAll(newItems);
          } else {
            pendingDrivers.addAll(newItems);
          }
          _offset += newItems.length;
          if (newItems.length < _limit) {
            hasMore.value = false;
          }
        }
      }
    } catch (e) {
      Get.snackbar("خطأ", "فشل جلب السائقين: $e");
    } finally {
      isLoading.value = false;
      isMoreLoading.value = false;
    }
  }

  Future<void> loadMore() async {
    await getPendingDrivers(refresh: false);
  }

  Future<Map<String, dynamic>?> getDriverFullDetails(String id) async {
    try {
      var response = await _crud.get(link: "${AppLink.getDriverDetails}?id=$id");
      if (response != null && response != 'failure' && response != 'token_expired') {
        var decoded = response is String ? jsonDecode(response) : response;
        if (decoded['status'] == "success") {
          return decoded['data'];
        }
      }
    } catch (e) {
      Get.snackbar("خطأ", "فشل جلب تفاصيل السائق: $e");
    }
    return null;
  }

  Future<bool> approveDriver(String id) async {
    isLoading.value = true;
    try {
      var response = await _crud.post(link: AppLink.updateDriverFromAdmin, payload: {
        "id": id,
        "status": "active",
      });
      if (response != null && response is Map && response['status'] == "success") {
        await getPendingDrivers();
        return true;
      }
      return false;
    } catch (e) {
      Get.snackbar("خطأ", "فشل اعتماد السائق: $e");
      return false;
    } finally {
      isLoading.value = false;
    }
  }
}
