import 'package:get/get.dart';
import 'package:on_field_work/helpers/services/app_logger.dart';
import 'package:on_field_work/helpers/services/api_service.dart';
import 'package:on_field_work/model/all_organization_model.dart';

class AllOrganizationController extends GetxController {
  RxList<AllOrganization> organizations = <AllOrganization>[].obs;
  Rxn<AllOrganization> selectedOrganization = Rxn<AllOrganization>();
  final isLoadingOrganizations = false.obs;

  String? passedOrgId;

  AllOrganizationController({this.passedOrgId});

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

  Future<void> fetchAllOrganizations() async {
    try {
      isLoadingOrganizations.value = true;

      final response = await ApiService.getAllOrganizations();
      if (response != null && response.data.data.isNotEmpty) {
        organizations.value = response.data.data;

        // Select organization based on passed ID, or fallback to first
        if (passedOrgId != null) {
          selectedOrganization.value =
              organizations.firstWhere(
                (org) => org.id == passedOrgId,
                orElse: () => organizations.first,
              );
        } else {
          selectedOrganization.value ??= organizations.first;
        }
      } else {
        organizations.clear();
        selectedOrganization.value = null;
      }
    } catch (e, stackTrace) {
      logSafe(
        "Failed to fetch organizations: $e",
        level: LogLevel.error,
        error: e,
        stackTrace: stackTrace,
      );
      organizations.clear();
      selectedOrganization.value = null;
    } finally {
      isLoadingOrganizations.value = false;
    }
  }

  void selectOrganization(AllOrganization? org) {
    selectedOrganization.value = org;
  }

  void clearSelection() {
    selectedOrganization.value = null;
  }

  String get currentSelection => selectedOrganization.value?.name ?? "All Organizations";
}
