import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/domain/models/community_model.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/domain/models/space_model.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_tile.dart';

class SpaceManagementCommunitiesTreeSpaceTile extends StatelessWidget {
  const SpaceManagementCommunitiesTreeSpaceTile({
    required this.space,
    required this.community,
    super.key,
  });

  final SpaceModel space;
  final CommunityModel community;

  @override
  Widget build(BuildContext context) {
    final spaceIsExpanded = _isSpaceOrChildSelected(context, space);
    final isSelected =
        context.watch<CommunitiesTreeSelectionBloc>().state.selectedSpace?.uuid ==
            space.uuid;
    return Padding(
      padding: const EdgeInsetsDirectional.only(start: 16.0),
      child: SpaceTile(
        title: space.spaceName,
        key: ValueKey(space.uuid),
        isSelected: isSelected,
        initiallyExpanded: spaceIsExpanded,
        onExpansionChanged: (expanded) {},
        onItemSelected: () => context.read<CommunitiesTreeSelectionBloc>().add(
              SelectSpaceEvent(community: community, space: space),
            ),
        children: space.children
            .map(
              (childSpace) => SpaceManagementCommunitiesTreeSpaceTile(
                space: childSpace,
                community: community,
              ),
            )
            .toList(),
      ),
    );
  }

  bool _isSpaceOrChildSelected(BuildContext context, SpaceModel space) {
    final selectedSpace =
        context.read<CommunitiesTreeSelectionBloc>().state.selectedSpace;
    final isSpaceSelected = selectedSpace?.uuid == space.uuid;
    final anySubSpaceIsSelected = space.children.any(
      (child) => _isSpaceOrChildSelected(context, child),
    );
    return isSpaceSelected || anySubSpaceIsSelected;
  }
}
