import 'package:get/get.dart';
import 'package:on_field_work/helpers/services/app_logger.dart';
import 'package:on_field_work/helpers/services/api_service.dart';
import 'package:on_field_work/model/employees/employee_model.dart';
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
import 'package:on_field_work/controller/directory/directory_controller.dart';

class ManageBucketController extends GetxController {
  RxList<EmployeeModel> allEmployees = <EmployeeModel>[].obs;
  RxBool isLoading = false.obs;

  final DirectoryController directoryController = Get.find();

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

  Future<bool> updateBucket({
    required String id,
    required String name,
    required String description,
    required List<String> employeeIds,
    required List<String> originalEmployeeIds,
  }) async {
    isLoading(true);
    update();

    try {
      final updated = await ApiService.updateBucket(
        id: id,
        name: name,
        description: description,
      );

      if (!updated) {
        showAppSnackbar(
          title: "Update Failed",
          message: "Unable to update bucket details.",
          type: SnackbarType.error,
        );
        isLoading(false);
        update();
        return false;
      }

      final allInvolvedIds = {...originalEmployeeIds, ...employeeIds}.toList();

      final assignPayload = allInvolvedIds.map((empId) {
        return {
          "employeeId": empId,
          "isActive": employeeIds.contains(empId),
        };
      }).toList();

      final assigned = await ApiService.assignEmployeesToBucket(
        bucketId: id,
        employees: assignPayload,
      );

      if (!assigned) {
        showAppSnackbar(
          title: "Assignment Failed",
          message: "Employees couldn't be updated.",
          type: SnackbarType.warning,
        );
      } else {
        showAppSnackbar(
          title: "Success",
          message: "Bucket updated successfully.",
          type: SnackbarType.success,
        );
      }

      return true;
    } catch (e, stack) {
      logSafe("Error in updateBucket: $e", level: LogLevel.error);
      logSafe("Stack: $stack", level: LogLevel.debug);
      showAppSnackbar(
        title: "Unexpected Error",
        message: "Please try again later.",
        type: SnackbarType.error,
      );
      return false;
    } finally {
      isLoading(false);
      update();
    }
  }

  Future<void> fetchAllEmployees() async {
    isLoading.value = true;

    try {
      final response = await ApiService.getAllEmployees();
      if (response != null && response.isNotEmpty) {
        allEmployees.assignAll(
            response.map((json) => EmployeeModel.fromJson(json)));
        logSafe(
          "All Employees fetched for Manage Bucket: ${allEmployees.length}",
          level: LogLevel.info,
        );
      } else {
        allEmployees.clear();
        logSafe("No employees found for Manage Bucket.",
            level: LogLevel.warning);
      }
    } catch (e) {
      allEmployees.clear();
      logSafe("Error fetching employees in Manage Bucket",
          level: LogLevel.error, error: e);
    }

    isLoading.value = false;
    update();
  }

  Future<void> deleteBucket(String bucketId) async {
    isLoading.value = true;
    update();

    try {
      final deleted = await ApiService.deleteBucket(bucketId);
      if (deleted) {
        directoryController.contactBuckets.removeWhere((b) => b.id == bucketId);
        showAppSnackbar(
          title: "Deleted",
          message: "Bucket deleted successfully.",
          type: SnackbarType.success,
        );
      } else {
        showAppSnackbar(
          title: "Delete Failed",
          message: "Unable to delete bucket.",
          type: SnackbarType.error,
        );
      }
    } catch (e, stack) {
      logSafe("Error deleting bucket: $e", level: LogLevel.error);
      logSafe("Stack: $stack", level: LogLevel.debug);
      showAppSnackbar(
        title: "Unexpected Error",
        message: "Failed to delete bucket.",
        type: SnackbarType.error,
      );
    } finally {
      isLoading.value = false;
      update();
    }
  }
}
