import 'package:flutter/material.dart';
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';
import '../../../core/storage/secure_storage.dart';
import '../../dashboard/controllers/dashboard_controller.dart';
import 'users_management_controller.dart';

class AddUserController extends GetxController {
  final nameController = TextEditingController();
  final emailController = TextEditingController();
  final phoneController = TextEditingController();
  
  var selectedRole = 'accountant'.obs;
  var isSubmitting = false.obs;
  
  var isSuperAdmin = false.obs;
  var tenants = <Map<String, dynamic>>[].obs;
  var selectedTenantId = RxnString();
  var isLoadingTenants = false.obs;
  
  final Dio _dio = DioClient().client;
  final SecureStorage _storage = SecureStorage();

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

  Future<void> _checkRoleAndFetchTenants() async {
    String role = '';
    
    // 1. Try to get from DashboardController first (fastest)
    if (Get.isRegistered<DashboardController>()) {
      role = Get.find<DashboardController>().userRole.value;
    }
    
    // 2. Fallback to SecureStorage
    if (role.isEmpty) {
      role = await _storage.read('user_role') ?? '';
    }

    if (role == 'super_admin') {
      isSuperAdmin.value = true;
      _fetchTenants();
    }
  }

  Future<void> _fetchTenants() async {
    try {
      isLoadingTenants.value = true;
      final response = await _dio.get('tenants');
      if (response.data['success'] == true) {
        tenants.value = List<Map<String, dynamic>>.from(response.data['data']);
        if (tenants.isNotEmpty) {
          selectedTenantId.value = tenants.first['id'];
        }
      }
    } catch (e) {
      AppLogger.error('Failed to fetch tenants for user creation', e);
    } finally {
      isLoadingTenants.value = false;
    }
  }

  @override
  void onClose() {
    nameController.dispose();
    emailController.dispose();
    phoneController.dispose();
    super.onClose();
  }

  Future<void> submit() async {
    final name = nameController.text.trim();
    final email = emailController.text.trim();
    final phone = phoneController.text.trim();

    if (name.isEmpty || email.isEmpty) {
      AppSnackbar.showWarning('تنبيه', 'الرجاء إدخال جميع البيانات الأساسية');
      return;
    }

    if (isSuperAdmin.value && selectedTenantId.value == null) {
      AppSnackbar.showWarning('تنبيه', 'الرجاء اختيار المكتب المحاسبي');
      return;
    }

    try {
      isSubmitting.value = true;
      final data = {
        'name': name,
        'email': email,
        'phone': phone,
        'role': selectedRole.value,
        'password': 'password123', // Default temporary password
      };
      
      if (isSuperAdmin.value) {
        data['tenant_id'] = selectedTenantId.value!;
      }

      final response = await _dio.post('users/create', data: data);

      if (response.statusCode == 200 || response.statusCode == 201) {
        AppSnackbar.showSuccess('نجاح', 'تم إضافة الموظف بنجاح');
        
        // Refresh the list if it exists
        if (Get.isRegistered<UsersManagementController>()) {
          Get.find<UsersManagementController>().fetchUsers();
        }
        
        Get.back();
      } else {
        AppSnackbar.showError('خطأ', 'فشل إضافة الموظف');
      }
    } catch (e) {
      AppLogger.error('Failed to create user', e);
      AppSnackbar.showError('خطأ', 'تعذر إضافة الموظف، يرجى المحاولة لاحقاً');
    } finally {
      isSubmitting.value = false;
    }
  }
}
