import 'package:bloc/bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'organization_event.dart';
import 'organization_state.dart';
import '../permission/permission_bloc.dart';
import '../permission/permission_event.dart';
import '../file_browser/file_browser_bloc.dart';
import '../file_browser/file_browser_event.dart';
import '../upload/upload_bloc.dart';
import '../upload/upload_event.dart';
import '../../services/org_api.dart';

class OrganizationBloc extends Bloc<OrganizationEvent, OrganizationState> {
  final PermissionBloc permissionBloc;
  final FileBrowserBloc fileBrowserBloc;
  final UploadBloc uploadBloc;
  final OrgApi orgApi;

  OrganizationBloc(
    this.permissionBloc,
    this.fileBrowserBloc,
    this.uploadBloc,
    this.orgApi,
  ) : super(OrganizationInitial()) {
    on<LoadOrganizations>(_onLoadOrganizations);
    on<SelectOrganization>(_onSelectOrganization);
    on<CreateOrganization>(_onCreateOrganization);
  }

  void _onLoadOrganizations(
    LoadOrganizations event,
    Emitter<OrganizationState> emit,
  ) async {
    emit(OrganizationLoading());
    try {
      final orgs = await orgApi.getOrganizations();
      emit(
        OrganizationLoaded(
          organizations: orgs,
          selectedOrg: orgs.isNotEmpty ? orgs.first : null,
        ),
      );
    } catch (e) {
      emit(OrganizationError(e.toString()));
    }
  }

  void _onSelectOrganization(
    SelectOrganization event,
    Emitter<OrganizationState> emit,
  ) {
    final currentState = state;
    if (currentState is OrganizationLoaded) {
      final selected = currentState.organizations.firstWhere(
        (org) => org.id == event.orgId,
        orElse: () => currentState.selectedOrg!,
      );
      emit(
        OrganizationLoaded(
          organizations: currentState.organizations,
          selectedOrg: selected,
          isLoading: false,
        ),
      );
      // Reset all dependent blocs
      permissionBloc.add(PermissionsReset());
      fileBrowserBloc.add(ResetFileBrowser());
      uploadBloc.add(ResetUploads());
      // Load permissions for the selected org
      permissionBloc.add(LoadPermissions(event.orgId));
    }
  }

  void _onCreateOrganization(
    CreateOrganization event,
    Emitter<OrganizationState> emit,
  ) async {
    final currentState = state;
    if (currentState is OrganizationLoaded) {
      final name = event.name.trim();
      if (name.isEmpty) {
        emit(
          OrganizationLoaded(
            organizations: currentState.organizations,
            selectedOrg: currentState.selectedOrg,
            isLoading: false,
            error: 'Organization name cannot be empty',
          ),
        );
        return;
      }
      if (currentState.organizations.any((org) => org.name == name)) {
        emit(
          OrganizationLoaded(
            organizations: currentState.organizations,
            selectedOrg: currentState.selectedOrg,
            isLoading: false,
            error: 'Organization with this name already exists',
          ),
        );
        return;
      }
      emit(
        OrganizationLoaded(
          organizations: currentState.organizations,
          selectedOrg: currentState.selectedOrg,
          isLoading: true,
        ),
      );
      try {
        final newOrg = await orgApi.createOrganization(name);
        final updatedOrgs = [...currentState.organizations, newOrg];
        emit(
          OrganizationLoaded(organizations: updatedOrgs, selectedOrg: newOrg),
        );
        // Reset blocs and load permissions for new org
        permissionBloc.add(PermissionsReset());
        fileBrowserBloc.add(ResetFileBrowser());
        uploadBloc.add(ResetUploads());
        permissionBloc.add(LoadPermissions(newOrg.id));
      } catch (e) {
        emit(
          OrganizationLoaded(
            organizations: currentState.organizations,
            selectedOrg: currentState.selectedOrg,
            isLoading: false,
            error: e.toString(),
          ),
        );
      }
    }
  }
}
