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 TenantSelectionController extends GetxController {
  final TenantService _tenantService = TenantService();

  // Tenant list
  final tenants = <Tenant>[].obs;

  // Loading state
  final isLoading = false.obs;

  // Selected tenant ID
  final selectedTenantId = RxnString();

  // Flag to indicate auto-selection (for splash screen)
  final isAutoSelecting = false.obs;

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

  /// Load tenants and handle auto-selection
  Future<void> loadTenants() async {
    isLoading.value = true;
    isAutoSelecting.value = true; // show splash during auto-selection
    try {
      final data = await _tenantService.getTenants();
      if (data == null || data.isEmpty) {
        tenants.clear();
        logSafe("⚠️ No tenants found for the user.", level: LogLevel.warning);
        return;
      }

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

      final recentTenantId = LocalStorage.getRecentTenantId();

      // Auto-select if only one tenant
      if (tenants.length == 1) {
        await _selectTenant(tenants.first.id);
      }
      // Auto-select recent tenant if available
      else if (recentTenantId != null) {
        final recentTenant =
            tenants.firstWhereOrNull((t) => t.id == recentTenantId);
        if (recentTenant != null) {
          await _selectTenant(recentTenant.id);
        } else {
          _clearSelection();
        }
      }
      // No auto-selection
      else {
        _clearSelection();
      }
    } catch (e, st) {
      logSafe("❌ Exception in loadTenants",
          level: LogLevel.error, error: e, stackTrace: st);
      showAppSnackbar(
        title: "Error",
        message: "Failed to load organizations. Please try again.",
        type: SnackbarType.error,
      );
    } finally {
      isLoading.value = false;
      isAutoSelecting.value = false; // hide splash
    }
  }

  /// User manually selects a tenant
  Future<void> onTenantSelected(String tenantId) async {
    isAutoSelecting.value = true;
    await _selectTenant(tenantId);
    isAutoSelecting.value = false;
  }

  /// Internal tenant selection logic
  Future<void> _selectTenant(String tenantId) async {
    try {
      isLoading.value = true;

      final success = await _tenantService.selectTenant(tenantId);
      if (!success) {
        showAppSnackbar(
          title: "Error",
          message: "Unable to select organization. Please try again.",
          type: SnackbarType.error,
        );
        return;
      }

      // Update tenant & persist
      final selectedTenant = tenants.firstWhere((t) => t.id == tenantId);
      TenantService.setSelectedTenant(selectedTenant);
      selectedTenantId.value = tenantId;
      await LocalStorage.setRecentTenantId(tenantId);

      // Load permissions if token exists
      final token = LocalStorage.getJwtToken();
      if (token != null && token.isNotEmpty) {
        if (!Get.isRegistered<PermissionController>()) {
          Get.put(PermissionController());
        }
        await Get.find<PermissionController>().loadData(token);
      }

      // Navigate **before changing isAutoSelecting**
      await Get.offAllNamed('/dashboard');

      // Then hide splash
      isAutoSelecting.value = false;
    } catch (e) {
      showAppSnackbar(
        title: "Error",
        message: "An unexpected error occurred while selecting organization.",
        type: SnackbarType.error,
      );
    } finally {
      isLoading.value = false;
    }
  }

  /// Clear tenant selection
  void _clearSelection() {
    selectedTenantId.value = null;
    TenantService.currentTenant = null;
  }
}
