import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/common/widgets/app_loading_indicator.dart';
import 'package:syncrow_web/common/widgets/search_bar.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/domain/params/load_communities_param.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/presentation/bloc/communities_bloc.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/presentation/widgets/communities_tree_failure_widget.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/presentation/widgets/empty_communities_tree_search_result_widget.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/presentation/widgets/space_management_communities_tree_community_tile.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/presentation/widgets/space_management_sidebar_communities_list.dart';
import 'package:syncrow_web/pages/space_management_v2/modules/communities/presentation/widgets/space_management_sidebar_header.dart';
import 'package:syncrow_web/utils/style.dart';

class SpaceManagementCommunitiesTree extends StatefulWidget {
  const SpaceManagementCommunitiesTree({super.key});

  @override
  State<SpaceManagementCommunitiesTree> createState() =>
      _SpaceManagementCommunitiesTreeState();
}

class _SpaceManagementCommunitiesTreeState
    extends State<SpaceManagementCommunitiesTree> {
  @override
  void initState() {
    context.read<CommunitiesBloc>().add(
          const LoadCommunities(LoadCommunitiesParam()),
        );
    super.initState();
  }

  void _onSearchChanged(String searchQuery) {
    context
        .read<CommunitiesBloc>()
        .add(LoadCommunities(LoadCommunitiesParam(search: searchQuery.trim())));
  }

  void _onLoadMore() {
    context.read<CommunitiesBloc>().add(const LoadMoreCommunities());
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CommunitiesBloc, CommunitiesState>(
      builder: (context, state) => Container(
        width: 320,
        decoration: subSectionContainerDecoration,
        child: Column(
          children: [
            const SpaceManagementSidebarHeader(),
            CustomSearchBar(
              onSearchChanged: _onSearchChanged,
            ),
            const SizedBox(height: 16),
            switch (state.status) {
              CommunitiesStatus.initial => const AppLoadingIndicator(),
              CommunitiesStatus.loading => state.communities.isEmpty
                  ? const AppLoadingIndicator()
                  : _buildCommunitiesTree(context, state),
              CommunitiesStatus.success => _buildCommunitiesTree(context, state),
              CommunitiesStatus.failure => CommunitiesTreeFailureWidget(
                  errorMessage: state.errorMessage,
                ),
            },
            Visibility(
              visible: state.isLoadingMore,
              child: const AppLoadingIndicator(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildCommunitiesTree(
    BuildContext context,
    CommunitiesState state,
  ) {
    final communitiesIsEmpty = state.communities.isEmpty;
    final statusIsSuccess = state.status == CommunitiesStatus.success;

    return Expanded(
      child: Visibility(
        visible: statusIsSuccess && communitiesIsEmpty,
        replacement: Stack(
          children: [
            SpaceManagementSidebarCommunitiesList(
              communities: state.communities,
              onLoadMore: state.hasNext ? _onLoadMore : null,
              isLoadingMore: state.isLoadingMore,
              hasNext: state.hasNext,
              itemBuilder: (context, index) {
                return SpaceManagementCommunitiesTreeCommunityTile(
                  community: state.communities[index],
                );
              },
            ),
            if (state.status == CommunitiesStatus.loading &&
                state.communities.isNotEmpty)
              ColoredBox(
                color: Colors.white.withValues(alpha: 0.7),
                child: const AppLoadingIndicator(),
              ),
          ],
        ),
        child: EmptyCommunitiesTreeSearchResultWidget(
          searchQuery: state.searchQuery,
        ),
      ),
    );
  }
}
