import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/space_management_v2/main_module/shared/helpers/space_management_community_dialog_helper.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/presentation/communities_tree_selection_bloc/communities_tree_selection_bloc.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/presentation/widgets/space_management_sidebar_add_community_button.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
import 'package:syncrow_web/utils/style.dart';

class SpaceManagementSidebarHeader extends StatelessWidget {
  const SpaceManagementSidebarHeader({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: subSectionContainerDecoration,
      padding: const EdgeInsets.all(16),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            'Communities',
            style: context.textTheme.titleMedium?.copyWith(
              color: ColorsManager.blackColor,
            ),
          ),
          SpaceManagementSidebarAddCommunityButton(
            onTap: () => _onAddCommunity(context),
          ),
        ],
      ),
    );
  }

  void _onAddCommunity(BuildContext context) {
    final bloc = context.read<CommunitiesTreeSelectionBloc>();
    final selectedCommunity = bloc.state.selectedCommunity;
    final isSelected = selectedCommunity?.uuid.isNotEmpty ?? false;

    if (isSelected) {
      _clearSelection(context);
    } else {
      SpaceManagementCommunityDialogHelper.showCreateDialog(context);
    }
  }

  void _clearSelection(BuildContext context) {
    context.read<CommunitiesTreeSelectionBloc>().add(
          const ClearCommunitiesTreeSelectionEvent(),
        );
  }
}
