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

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

  var tenants = <Tenant>[].obs;
  var isLoading = false.obs;

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

  /// Load tenants from API
  Future<void> loadTenants({bool fromTenantSelectionScreen = false}) async {
    try {
      isLoading.value = true;
      final data = await _tenantService.getTenants();
      if (data != null) {
        tenants.value = data.map((e) => Tenant.fromJson(e)).toList();

        final recentTenantId = LocalStorage.getRecentTenantId();

        // ✅ If user came from TenantSelectionScreen & recent tenant exists, auto-select
        if (fromTenantSelectionScreen && recentTenantId != null) {
          final tenantExists = tenants.any((t) => t.id == recentTenantId);
          if (tenantExists) {
            await onTenantSelected(recentTenantId);
            return;
          } else {
            // if tenant is no longer valid, clear recentTenant
            await LocalStorage.removeRecentTenantId();
          }
        }

        // ✅ Auto-select if only one tenant
        if (tenants.length == 1) {
          await onTenantSelected(tenants.first.id);
        }
      } else {
        tenants.clear();
        logSafe("⚠️ No tenants found for the user.", level: LogLevel.warning);
      }
    } catch (e, st) {
      logSafe("❌ Exception in loadTenants",
          level: LogLevel.error, error: e, stackTrace: st);
    } finally {
      isLoading.value = false;
    }
  }

  /// Select tenant
  Future<void> onTenantSelected(String tenantId) async {
    try {
      isLoading.value = true;
      final success = await _tenantService.selectTenant(tenantId);
      if (success) {
        logSafe("✅ Tenant selection successful: $tenantId");

        // Store selected tenant in memory
        final selectedTenant = tenants.firstWhere((t) => t.id == tenantId);
        TenantService.setSelectedTenant(selectedTenant);

        // 🔥 Save in LocalStorage
        await LocalStorage.setRecentTenantId(tenantId);

        // Navigate to dashboard
        Get.offAllNamed('/dashboard');

        showAppSnackbar(
          title: "Success",
          message: "Organization selected successfully.",
          type: SnackbarType.success,
        );
      } else {
        logSafe("❌ Tenant selection failed for: $tenantId",
            level: LogLevel.warning);

        // Show error snackbar
        showAppSnackbar(
          title: "Error",
          message: "Unable to select organization. Please try again.",
          type: SnackbarType.error,
        );
      }
    } catch (e, st) {
      logSafe("❌ Exception in onTenantSelected",
          level: LogLevel.error, error: e, stackTrace: st);

      // Show error snackbar for exception
      showAppSnackbar(
        title: "Error",
        message: "An unexpected error occurred while selecting organization.",
        type: SnackbarType.error,
      );
    } finally {
      isLoading.value = false;
    }
  }
}
