import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/common/widgets/search_bar.dart';
import 'package:syncrow_web/common/widgets/sidebar_communities_list.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_bloc.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_event.dart';
import 'package:syncrow_web/pages/space_tree/bloc/space_tree_state.dart';
import 'package:syncrow_web/pages/space_tree/view/custom_expansion.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/community_model.dart';
import 'package:syncrow_web/pages/spaces_management/all_spaces/model/space_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';

class AnalyticsSpaceTreeView extends StatefulWidget {
  const AnalyticsSpaceTreeView({
    super.key,
    this.onSelectCommunity,
    this.onSelectSpace,
    this.onSelectChildSpace,
  });

  final void Function(
    CommunityModel community,
    List<SpaceModel> spaces,
  )? onSelectCommunity;
  final void Function(
    CommunityModel community,
    SpaceModel space,
  )? onSelectSpace;
  final void Function(
    CommunityModel community,
    SpaceModel child,
  )? onSelectChildSpace;

  @override
  State<AnalyticsSpaceTreeView> createState() => _AnalyticsSpaceTreeViewState();
}

class _AnalyticsSpaceTreeViewState extends State<AnalyticsSpaceTreeView> {
  late final ScrollController _scrollController;

  @override
  void initState() {
    _scrollController = ScrollController();
    super.initState();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<SpaceTreeBloc, SpaceTreeState>(builder: (context, state) {
      final communities = state.searchQuery.isNotEmpty
          ? state.filteredCommunity
          : state.communityList;
      return Container(
        height: MediaQuery.sizeOf(context).height,
        decoration: const BoxDecoration(color: ColorsManager.whiteColors),
        child: state is SpaceTreeLoadingState
            ? const Center(child: CircularProgressIndicator())
            : Column(
                children: [
                  Container(
                    alignment: AlignmentDirectional.centerStart,
                    padding: const EdgeInsets.all(24),
                    child: DefaultTextStyle(
                      style: context.textTheme.titleMedium!.copyWith(
                        color: ColorsManager.blackColor,
                        fontSize: 20,
                      ),
                      child: const Text('Communities'),
                    ),
                  ),
                  CustomSearchBar(
                    onSearchChanged: (query) => context.read<SpaceTreeBloc>().add(
                          SearchQueryEvent(query),
                        ),
                  ),
                  const SizedBox(height: 16),
                  Expanded(
                    child: state.isSearching
                        ? const Center(child: CircularProgressIndicator())
                        : SidebarCommunitiesList(
                            onScrollToEnd: () {
                              if (!state.paginationIsLoading) {
                                context.read<SpaceTreeBloc>().add(
                                      PaginationEvent(
                                        state.paginationModel,
                                        state.communityList,
                                      ),
                                    );
                              }
                            },
                            scrollController: _scrollController,
                            communities: communities,
                            itemBuilder: (context, index) {
                              return CustomExpansionTileSpaceTree(
                                title: communities[index].name,
                                isSelected: state.selectedCommunities
                                    .contains(communities[index].uuid),
                                isSoldCheck: state.selectedCommunities
                                    .contains(communities[index].uuid),
                                onExpansionChanged: () =>
                                    context.read<SpaceTreeBloc>().add(
                                          OnCommunityExpanded(
                                            communities[index].uuid,
                                          ),
                                        ),
                                isExpanded: state.expandedCommunities.contains(
                                  communities[index].uuid,
                                ),
                                onItemSelected: () => widget.onSelectCommunity?.call(
                                  communities[index],
                                  communities[index].spaces,
                                ),
                                children: communities[index].spaces.map(
                                  (space) {
                                    return CustomExpansionTileSpaceTree(
                                      title: space.name,
                                      isExpanded:
                                          state.expandedSpaces.contains(space.uuid),
                                      onItemSelected: () =>
                                          widget.onSelectSpace?.call(
                                        communities[index],
                                        space,
                                      ),
                                      onExpansionChanged: () =>
                                          context.read<SpaceTreeBloc>().add(
                                                OnSpaceExpanded(
                                                  communities[index].uuid,
                                                  space.uuid ?? '',
                                                ),
                                              ),
                                      isSelected: state.selectedSpaces
                                              .contains(space.uuid) ||
                                          state.soldCheck.contains(space.uuid),
                                      isSoldCheck:
                                          state.soldCheck.contains(space.uuid),
                                      children: _buildNestedSpaces(
                                        context,
                                        state,
                                        space,
                                        communities[index],
                                      ),
                                    );
                                  },
                                ).toList(),
                              );
                            },
                          ),
                  ),
                  if (state.paginationIsLoading) const CircularProgressIndicator(),
                ],
              ),
      );
    });
  }

  List<Widget> _buildNestedSpaces(
    BuildContext context,
    SpaceTreeState state,
    SpaceModel space,
    CommunityModel community,
  ) {
    return space.children.map((child) {
      return CustomExpansionTileSpaceTree(
        isSelected: state.selectedSpaces.contains(child.uuid) ||
            state.soldCheck.contains(child.uuid),
        isSoldCheck: state.soldCheck.contains(child.uuid),
        title: child.name,
        isExpanded: state.expandedSpaces.contains(child.uuid),
        onItemSelected: () {
          widget.onSelectChildSpace?.call(community, child);
        },
        onExpansionChanged: () {
          context.read<SpaceTreeBloc>().add(
                OnSpaceExpanded(community.uuid, child.uuid ?? ''),
              );
        },
        children: _buildNestedSpaces(context, state, child, community),
      );
    }).toList();
  }
}
