import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_bloc.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_event.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/bloc/users_status.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/model/tree_node_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';

class TreeView extends StatelessWidget {
  final String? userId;

  const TreeView({
    super.key,
    this.userId,
  });

  @override
  Widget build(BuildContext context) {
    final _blocRole = BlocProvider.of<UsersBloc>(context);
    return BlocProvider(
      create: (_) => UsersBloc(),
      // ..add(const LoadCommunityAndSpacesEvent()),
      child: BlocConsumer<UsersBloc, UsersState>(
        listener: (context, state) {
          // if (state is SpacesLoadedState) {
          //   _blocRole.add(GetUserByIdEvent(uuid: userId));
          // }
        },
        builder: (context, state) {
          if (state is UsersLoadingState) {
            return const Center(child: CircularProgressIndicator());
          }
          return SingleChildScrollView(
            child: _buildTree(_blocRole.updatedCommunities, _blocRole),
          );
        },
      ),
    );
  }

  Widget _buildTree(
    List<TreeNode> nodes,
    UsersBloc bloc, {
    int level = 0,
  }) {
    return Column(
      children: nodes.map((node) {
        return Container(
          color: node.isHighlighted ? Colors.blue.shade50 : Colors.transparent,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: const EdgeInsets.all(5.0),
                child: Row(
                  children: [
                    /// Checkbox (GestureDetector)
                    GestureDetector(
                      onTap: () {
                        bloc.add(ToggleNodeCheck(node));
                      },
                      child: Image.asset(
                        _getCheckBoxImage(node),
                        width: 20,
                        height: 20,
                      ),
                    ),
                    const SizedBox(width: 15),
                    Expanded(
                      child: Padding(
                        padding: EdgeInsets.only(left: level * 10.0),
                        child: Row(
                          children: [
                            GestureDetector(
                              onTap: () {
                                bloc.add(ToggleNodeExpansion(node: node));
                              },
                              child: node.children.isNotEmpty
                                  ? SvgPicture.asset(
                                      node.isExpanded
                                          ? Assets.arrowDown
                                          : Assets.arrowForward,
                                      fit: BoxFit.none,
                                    )
                                  : const SizedBox(width: 16),
                            ),
                            const SizedBox(width: 20),
                            Text(
                              node.title,
                              style: TextStyle(
                                fontSize: 16,
                                color: node.isHighlighted
                                    ? ColorsManager.blackColor
                                    : ColorsManager.textGray,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              if (node.isExpanded)
                _buildTree(
                  node.children,
                  bloc,
                  level: level + 1,
                ),
            ],
          ),
        );
      }).toList(),
    );
  }

  String _getCheckBoxImage(TreeNode node) {
    if (node.children.isEmpty) {
      return node.isChecked ? Assets.CheckBoxChecked : Assets.emptyBox;
    }
    if (_areAllChildrenChecked(node)) {
      return Assets.CheckBoxChecked;
    } else if (_areSomeChildrenChecked(node)) {
      return Assets.rectangleCheckBox;
    } else {
      return Assets.emptyBox;
    }
  }

  bool _areAllChildrenChecked(TreeNode node) {
    return node.children.isNotEmpty &&
        node.children.every((child) =>
            child.isChecked &&
            (child.children.isEmpty || _areAllChildrenChecked(child)));
  }

  bool _areSomeChildrenChecked(TreeNode node) {
    return node.children.isNotEmpty &&
        node.children.any((child) =>
            child.isChecked ||
            (child.children.isNotEmpty && _areSomeChildrenChecked(child)));
  }
}
