import 'package:get/get.dart';
import 'package:dio/dio.dart';
import '../../../core/network/dio_client.dart';
import '../../../core/utils/app_snackbar.dart';
import '../../../core/utils/logger.dart';

class UsersManagementController extends GetxController {
  final Dio _dio = DioClient().client;

  var isLoading = true.obs;
  var users = <Map<String, dynamic>>[].obs;

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

  Future<void> fetchUsers() async {
    try {
      isLoading.value = true;
      final response = await _dio.get('users');
      if (response.data['success'] == true) {
        users.value = List<Map<String, dynamic>>.from(response.data['data']);
      }
    } catch (e) {
      AppLogger.error('Failed to fetch users', e);
      AppSnackbar.showError('خطأ', 'تعذر تحميل قائمة الموظفين');
    } finally {
      isLoading.value = false;
    }
  }

  Future<void> updateUser(String id, Map<String, dynamic> data) async {
    try {
      data['id'] = id;
      final response = await _dio.post('users/update', data: data);
      if (response.data['success'] == true) {
        await fetchUsers();
        AppSnackbar.showSuccess('نجاح', 'تم تحديث بيانات المستخدم');
      }
    } catch (e) {
      AppLogger.error('Failed to update user', e);
      AppSnackbar.showError('خطأ', 'تعذر تحديث المستخدم');
    }
  }

  Future<void> deleteUser(String id) async {
    try {
      final response = await _dio.post('users/delete', data: {'id': id});
      if (response.data['success'] == true) {
        users.removeWhere((u) => u['id'] == id);
        AppSnackbar.showSuccess('نجاح', 'تم حذف المستخدم بنجاح');
      }
    } catch (e) {
      AppLogger.error('Failed to delete user', e);
      AppSnackbar.showError('خطأ', 'تعذر حذف المستخدم');
    }
  }

  Future<void> toggleUserActive(String id, bool isActive) async {
    await updateUser(id, {'is_active': isActive});
  }
}
