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

class QualityController extends GetxController {
  bool isLoading = false;
  List driversBlacklist = [];
  List passengersBlacklist = [];
  Map scorecardData = {};

  Future<void> fetchBlacklist() async {
    isLoading = true;
    update();
    try {
      var res = await CRUD().post(
        link: AppLink.blacklistManager,
        payload: {"action_type": "get_all"},
      );
      if (res is Map && res['status'] == 'success') {
        driversBlacklist = res['message']['drivers'] ?? [];
        passengersBlacklist = res['message']['passengers'] ?? [];
      } else {
        Get.snackbar("Error", "Failed to fetch blacklist");
      }
    } catch (e) {
      Get.snackbar("Error", "Network error");
    } finally {
      isLoading = false;
      update();
    }
  }

  Future<void> unblockDriver(String phone) async {
    try {
      var res = await CRUD().post(
        link: AppLink.blacklistManager,
        payload: {
          "action_type": "unblock_driver",
          "phone": phone,
        },
      );
      if (res is Map && res['status'] == 'success') {
        Get.snackbar("Success", "Driver unblocked successfully");
        fetchBlacklist(); // Refresh
      } else {
        Get.snackbar("Error", res['message'] ?? "Failed to unblock driver");
      }
    } catch (e) {
      Get.snackbar("Error", "Network error");
    }
  }

  Future<void> unblockPassenger(String phoneNormalized) async {
    try {
      var res = await CRUD().post(
        link: AppLink.blacklistManager,
        payload: {
          "action_type": "unblock_passenger",
          "phone_normalized": phoneNormalized,
        },
      );
      if (res is Map && res['status'] == 'success') {
        Get.snackbar("Success", "Passenger unblocked successfully");
        fetchBlacklist(); // Refresh
      } else {
        Get.snackbar("Error", res['message'] ?? "Failed to unblock passenger");
      }
    } catch (e) {
      Get.snackbar("Error", "Network error");
    }
  }

  Future<void> fetchDriverScorecard(String driverId) async {
    isLoading = true;
    update();
    try {
      var res = await CRUD().post(
        link: AppLink.driverScorecard,
        payload: {"driver_id": driverId},
      );
      if (res is Map && res['status'] == 'success') {
        scorecardData = res['message'];
      } else {
        Get.snackbar("Error", "Failed to fetch scorecard");
        scorecardData = {};
      }
    } catch (e) {
      Get.snackbar("Error", "Network error");
      scorecardData = {};
    } finally {
      isLoading = false;
      update();
    }
  }

  @override
  void onInit() {
    super.onInit();
    // fetchBlacklist() can be called when opening the page
  }
}
