import 'package:get/get.dart';
import 'package:on_field_work/helpers/services/app_logger.dart';
import 'package:on_field_work/helpers/services/tenant_service.dart';
import 'package:on_field_work/model/tenant/tenant_list_model.dart';
import 'package:on_field_work/helpers/widgets/my_snackbar.dart';
import 'package:on_field_work/helpers/services/storage/local_storage.dart';
import 'package:on_field_work/controller/permission_controller.dart';

class TenantSwitchController extends GetxController {
  final TenantService _tenantService = TenantService();

  final tenants = <Tenant>[].obs;
  final isLoading = false.obs;
  final selectedTenantId = RxnString();

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

  /// Load all tenants for switching (does not auto-select)
  Future<void> loadTenants() async {
    isLoading.value = true;
    try {
      final data = await _tenantService.getTenants();
      if (data == null || data.isEmpty) {
        tenants.clear();
        logSafe("⚠️ No tenants available for switching.", level: LogLevel.warning);
        return;
      }

      tenants.value = data.map((e) => Tenant.fromJson(e)).toList();

      // Keep current tenant as selected
      selectedTenantId.value = TenantService.currentTenant?.id;
    } catch (e, st) {
      logSafe("❌ Exception in loadTenants", level: LogLevel.error, error: e, stackTrace: st);
      showAppSnackbar(
        title: "Error",
        message: "Failed to load organizations for switching.",
        type: SnackbarType.error,
      );
    } finally {
      isLoading.value = false;
    }
  }

  /// Switch to a different tenant and navigate fully
  Future<void> switchTenant(String tenantId) async {
    if (TenantService.currentTenant?.id == tenantId) return; 

    isLoading.value = true;
    try {
      final success = await _tenantService.selectTenant(tenantId);
      if (!success) {
        logSafe("❌ Tenant switch failed: $tenantId", level: LogLevel.warning);
        showAppSnackbar(
          title: "Error",
          message: "Unable to switch organization. Try again.",
          type: SnackbarType.error,
        );
        return;
      }

      final selectedTenant = tenants.firstWhere((t) => t.id == tenantId);
      TenantService.setSelectedTenant(selectedTenant);
      selectedTenantId.value = tenantId;

      // Persist recent tenant
      await LocalStorage.setRecentTenantId(tenantId);

      logSafe("✅ Tenant switched successfully: $tenantId");

      // 🔹 Load permissions after tenant switch (null-safe)
      final token = await LocalStorage.getJwtToken();
      if (token != null && token.isNotEmpty) {
        if (!Get.isRegistered<PermissionController>()) {
          Get.put(PermissionController());
          logSafe("✅ PermissionController injected after tenant switch.");
        }
        await Get.find<PermissionController>().loadData(token);
      } else {
        logSafe("⚠️ JWT token is null. Cannot load permissions.", level: LogLevel.warning);
      }

      // FULL NAVIGATION: reload app/dashboard
      Get.offAllNamed('/dashboard');

      showAppSnackbar(
        title: "Success",
        message: "Switched to organization: ${selectedTenant.name}",
        type: SnackbarType.success,
      );
    } catch (e, st) {
      logSafe("❌ Exception in switchTenant", level: LogLevel.error, error: e, stackTrace: st);
      showAppSnackbar(
        title: "Error",
        message: "An unexpected error occurred while switching organization.",
        type: SnackbarType.error,
      );
    } finally {
      isLoading.value = false;
    }
  }
}
