import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:number_pagination/number_pagination.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/view/add_user_dialog.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/view/delete_user_dialog.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/view/edit_user_dialog.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/view/popup_menu_filter.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/users_table/bloc/user_table_bloc.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/users_table/bloc/user_table_event.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/users_table/bloc/user_table_state.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/users_table/view/creation_date_filter.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/users_table/view/de_activate_filter.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/users_table/view/name_filter.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/users_table/view/user_table.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/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
import 'package:syncrow_web/utils/style.dart';

class UsersPage extends StatelessWidget {
  UsersPage({super.key});

  @override
  Widget build(BuildContext context) {
    final TextEditingController searchController = TextEditingController();

    Widget actionButton(
        {bool isActive = false, required String title, Function()? onTap}) {
      return InkWell(
        onTap: onTap,
        child: Padding(
          padding: const EdgeInsets.only(left: 8, right: 8),
          child: Text(
            title,
            style: Theme.of(context).textTheme.bodySmall?.copyWith(
                  color: isActive == false && title != "Delete"
                      ? Colors.grey
                      : title == "Delete"
                          ? ColorsManager.red
                          : ColorsManager.spaceColor,
                  fontWeight: FontWeight.w400,
                ),
          ),
        ),
      );
    }

    Widget status({required String status}) {
      return Center(
        child: Container(
          padding: const EdgeInsets.only(left: 5, right: 5, bottom: 5, top: 5),
          decoration: BoxDecoration(
            borderRadius: const BorderRadius.all(Radius.circular(20)),
            color: status == "invited"
                ? ColorsManager.invitedOrange.withOpacity(0.5)
                : status == "active"
                    ? ColorsManager.activeGreen.withOpacity(0.5)
                    : ColorsManager.disabledPink.withOpacity(0.5),
          ),
          child: Padding(
            padding:
                const EdgeInsets.only(left: 10, right: 10, bottom: 5, top: 5),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  status,
                  style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        color: status == "invited"
                            ? ColorsManager.invitedOrangeText
                            : status == "active"
                                ? ColorsManager.activeGreenText
                                : ColorsManager.disabledRedText,
                        fontWeight: FontWeight.w400,
                      ),
                ),
              ],
            ),
          ),
        ),
      );
    }

    Widget changeIconStatus(
        {required String userId,
        required String status,
        required Function()? onTap}) {
      return Center(
        child: InkWell(
          onTap: onTap,
          child: Padding(
            padding:
                const EdgeInsets.only(left: 5, right: 5, bottom: 5, top: 5),
            child: SvgPicture.asset(
              status == "invited"
                  ? Assets.invitedIcon
                  : status == "active"
                      ? Assets.activeUser
                      : Assets.deActiveUser,
              height: 35,
            ),
          ),
        ),
      );
    }

    return BlocBuilder<UserTableBloc, UserTableState>(
      builder: (context, state) {
        final screenSize = MediaQuery.of(context).size;
        final _blocRole = BlocProvider.of<UserTableBloc>(context);
        if (state is UsersLoadingState) {
          return const Center(child: CircularProgressIndicator());
        } else if (state is UsersLoadedState) {
          return Padding(
            padding: const EdgeInsets.all(20),
            child: Align(
              alignment: Alignment.topCenter,
              child: Column(
                children: [
                  Row(
                    children: [
                      Container(
                        decoration: containerDecoration.copyWith(
                          borderRadius: const BorderRadius.all(
                            Radius.circular(20),
                          ),
                        ),
                        width: screenSize.width * 0.4,
                        child: TextFormField(
                          controller: searchController,
                          onChanged: (value) {
                            final bloc = context.read<UserTableBloc>();
                            bloc.add(FilterClearEvent());
                            bloc.add(SearchUsers(value));
                            if (value == '') {
                              bloc.add(ChangePage(1));
                            }
                          },
                          style: const TextStyle(color: Colors.black),
                          decoration: textBoxDecoration(radios: 15)!.copyWith(
                            fillColor: ColorsManager.whiteColors,
                            errorStyle: const TextStyle(height: 0),
                            hintStyle: context.textTheme.titleSmall?.copyWith(
                              color: Colors.grey,
                              fontSize: 12,
                            ),
                            hintText: 'Search',
                            suffixIcon: SizedBox(
                              child: SvgPicture.asset(
                                Assets.searchIconUser,
                                fit: BoxFit.none,
                              ),
                            ),
                          ),
                        ),
                      ),
                      const SizedBox(width: 20),
                      InkWell(
                        onTap: () {
                          context.read<SpaceTreeBloc>().add(ClearCachedData());
                          showDialog(
                            context: context,
                            barrierDismissible: false,
                            builder: (BuildContext context) {
                              return const AddNewUserDialog();
                            },
                          ).then((v) {
                            if (v != null) {
                              _blocRole.add(const GetUsers());
                            }
                          });
                        },
                        child: Container(
                          decoration: containerWhiteDecoration,
                          width: screenSize.width * 0.18,
                          height: 50,
                          child: const Center(
                            child: Text(
                              'Add New User',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w700,
                                color: ColorsManager.blueColor,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 20),
                  Container(
                    height: screenSize.height * 0.65,
                    child: DynamicTableScreen(
                      tableSize: screenSize.height * 0.65,
                      onFilter: (columnIndex) {
                        if (columnIndex == 0) {
                          showNameMenu(
                            context: context,
                            isSelected: _blocRole.currentSortOrder,
                            aToZTap: () {
                              context
                                  .read<UserTableBloc>()
                                  .add(const SortUsersByNameAsc());
                            },
                            zToATap: () {
                              context
                                  .read<UserTableBloc>()
                                  .add(const SortUsersByNameDesc());
                            },
                          );
                        }
                        if (columnIndex == 2) {
                          final Map<String, bool> checkboxStates = {
                            for (var item in _blocRole.jobTitle)
                              item: _blocRole.selectedJobTitles.contains(item),
                          };
                          final RenderBox overlay = Overlay.of(context)
                              .context
                              .findRenderObject() as RenderBox;

                          showPopUpFilterMenu(
                            position: RelativeRect.fromLTRB(
                              overlay.size.width / 5.3,
                              240,
                              overlay.size.width / 4,
                              0,
                            ),
                            list: _blocRole.jobTitle,
                            context: context,
                            checkboxStates: checkboxStates,
                            isSelected: _blocRole.currentSortJopTitle,
                            onOkPressed: () {
                              searchController.clear();
                              _blocRole.add(FilterClearEvent());
                              final selectedItems = checkboxStates.entries
                                  .where((entry) => entry.value)
                                  .map((entry) => entry.key)
                                  .toList();
                              Navigator.of(context).pop();
                              _blocRole.add(FilterUsersByJobEvent(
                                selectedJob: selectedItems,
                                sortOrder: _blocRole.currentSortJopTitle,
                              ));
                            },
                            onSortAtoZ: (v) {
                              _blocRole.currentSortJopTitle = v;
                            },
                            onSortZtoA: (v) {
                              _blocRole.currentSortJopTitle = v;
                            },
                          );
                        }

                        if (columnIndex == 3) {
                          final Map<String, bool> checkboxStates = {
                            for (var item in _blocRole.roleTypes)
                              item: _blocRole.selectedRoles.contains(item),
                          };
                          final RenderBox overlay = Overlay.of(context)
                              .context
                              .findRenderObject() as RenderBox;
                          showPopUpFilterMenu(
                            position: RelativeRect.fromLTRB(
                              overlay.size.width / 4,
                              240,
                              overlay.size.width / 4,
                              0,
                            ),
                            list: _blocRole.roleTypes,
                            context: context,
                            checkboxStates: checkboxStates,
                            isSelected: _blocRole.currentSortRole,
                            onOkPressed: () {
                              searchController.clear();
                              _blocRole.add(FilterClearEvent());
                              final selectedItems = checkboxStates.entries
                                  .where((entry) => entry.value)
                                  .map((entry) => entry.key)
                                  .toList();
                              Navigator.of(context).pop();
                              context.read<UserTableBloc>().add(
                                  FilterUsersByRoleEvent(
                                      selectedRoles: selectedItems,
                                      sortOrder: _blocRole.currentSortRole));
                            },
                            onSortAtoZ: (v) {
                              _blocRole.currentSortRole = v;
                            },
                            onSortZtoA: (v) {
                              _blocRole.currentSortRole = v;
                            },
                          );
                        }
                        if (columnIndex == 4) {
                          showDateFilterMenu(
                            context: context,
                            isSelected: _blocRole.currentSortOrder,
                            aToZTap: () {
                              context
                                  .read<UserTableBloc>()
                                  .add(const DateNewestToOldestEvent());
                            },
                            zToaTap: () {
                              context
                                  .read<UserTableBloc>()
                                  .add(const DateOldestToNewestEvent());
                            },
                          );
                        }
                        if (columnIndex == 6) {
                          final Map<String, bool> checkboxStates = {
                            for (var item in _blocRole.createdBy)
                              item: _blocRole.selectedCreatedBy.contains(item),
                          };
                          final RenderBox overlay = Overlay.of(context)
                              .context
                              .findRenderObject() as RenderBox;
                          showPopUpFilterMenu(
                            position: RelativeRect.fromLTRB(
                              overlay.size.width / 1,
                              240,
                              overlay.size.width / 4,
                              0,
                            ),
                            list: _blocRole.createdBy,
                            context: context,
                            checkboxStates: checkboxStates,
                            isSelected: _blocRole.currentSortCreatedBy,
                            onOkPressed: () {
                              searchController.clear();
                              _blocRole.add(FilterClearEvent());
                              final selectedItems = checkboxStates.entries
                                  .where((entry) => entry.value)
                                  .map((entry) => entry.key)
                                  .toList();
                              Navigator.of(context).pop();
                              _blocRole.add(FilterUsersByCreatedEvent(
                                  selectedCreatedBy: selectedItems,
                                  sortOrder: _blocRole.currentSortCreatedBy));
                            },
                            onSortAtoZ: (v) {
                              _blocRole.currentSortCreatedBy = v;
                            },
                            onSortZtoA: (v) {
                              _blocRole.currentSortCreatedBy = v;
                            },
                          );
                        }
                        if (columnIndex == 7) {
                          final Map<String, bool> checkboxStates = {
                            for (var item in _blocRole.status)
                              item: _blocRole.selectedStatuses.contains(item),
                          };

                          final RenderBox overlay = Overlay.of(context)
                              .context
                              .findRenderObject() as RenderBox;
                          showPopUpFilterMenu(
                            position: RelativeRect.fromLTRB(
                              overlay.size.width / 0,
                              240,
                              overlay.size.width / 5,
                              0,
                            ),
                            list: _blocRole.status,
                            context: context,
                            checkboxStates: checkboxStates,
                            isSelected: _blocRole.currentSortStatus,
                            onOkPressed: () {
                              searchController.clear();
                              _blocRole.add(FilterClearEvent());
                              final selectedItems = checkboxStates.entries
                                  .where((entry) => entry.value)
                                  .map((entry) => entry.key)
                                  .toList();
                              Navigator.of(context).pop();
                              _blocRole.add(FilterUsersByDeActevateEvent(
                                  selectedActivate: selectedItems,
                                  sortOrder: _blocRole.currentSortStatus));
                            },
                            onSortAtoZ: (v) {
                              _blocRole.currentSortStatus = v;
                            },
                            onSortZtoA: (v) {
                              _blocRole.currentSortStatus = v;
                            },
                          );
                        }
                        if (columnIndex == 8) {
                          showDeActivateFilterMenu(
                            context: context,
                            isSelected: _blocRole.currentSortOrderDate,
                            aToZTap: () {
                              context
                                  .read<UserTableBloc>()
                                  .add(const DateNewestToOldestEvent());
                            },
                            zToaTap: () {
                              context
                                  .read<UserTableBloc>()
                                  .add(const DateOldestToNewestEvent());
                            },
                          );
                        }
                      },
                      titles: const [
                        "Full Name",
                        "Email Address",
                        "Job Title",
                        "Role",
                        "Creation Date",
                        "Creation Time",
                        "Created By",
                        "Status",
                        "De/Activate",
                        "Action"
                      ],
                      rows: state.users.map((user) {
                        return [
                          Text('${user.firstName} ${user.lastName}'),
                          Text(user.email),
                          Text(user.jobTitle),
                          Text(user.roleType ?? ''),
                          Text(user.createdDate ?? ''),
                          Text(user.createdTime ?? ''),
                          Text(user.invitedBy),
                          status(
                            status: user.isEnabled == false
                                ? 'disabled'
                                : user.status,
                          ),
                          changeIconStatus(
                            status: user.isEnabled == false
                                ? 'disabled'
                                : user.status,
                            userId: user.uuid,
                            onTap: user.status != "invited"
                                ? () {
                                    context.read<UserTableBloc>().add(
                                        ChangeUserStatus(
                                            userId: user.uuid,
                                            newStatus: user.isEnabled == false
                                                ? 'disabled'
                                                : user.status));
                                  }
                                : null,
                          ),
                          Row(
                            children: [
                              if (user.isEnabled != false)
                                actionButton(
                                  isActive: true,
                                  title: "Edit",
                                  onTap: () {
                                    context
                                        .read<SpaceTreeBloc>()
                                        .add(ClearCachedData());
                                    showDialog(
                                      context: context,
                                      barrierDismissible: false,
                                      builder: (BuildContext context) {
                                        return EditUserDialog(user: user);
                                      },
                                    ).then((v) {
                                      if (v != null) {
                                        _blocRole.add(const GetUsers());
                                      }
                                    });
                                  },
                                )
                              else
                                actionButton(
                                  title: "Edit",
                                ),
                              actionButton(
                                title: "Delete",
                                onTap: () {
                                  showDialog(
                                    context: context,
                                    barrierDismissible: false,
                                    builder: (BuildContext context) {
                                      return DeleteUserDialog(
                                          onTapDelete: () async {
                                        try {
                                          _blocRole.add(DeleteUserEvent(
                                              user.uuid, context));
                                          await Future.delayed(
                                              const Duration(seconds: 2));
                                          return true;
                                        } catch (e) {
                                          return false;
                                        }
                                      });
                                    },
                                  ).then((v) {
                                    if (v != null) {
                                      _blocRole.add(const GetUsers());
                                    }
                                  });
                                },
                              ),
                            ],
                          ),
                        ];
                      }).toList(),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        SizedBox(
                          width: 500,
                          child: NumberPagination(
                            visiblePagesCount: 4,
                            buttonRadius: 10,
                            selectedButtonColor: ColorsManager.secondaryColor,
                            buttonUnSelectedBorderColor:
                                ColorsManager.grayBorder,
                            lastPageIcon:
                                const Icon(Icons.keyboard_double_arrow_right),
                            firstPageIcon:
                                const Icon(Icons.keyboard_double_arrow_left),
                            totalPages: (_blocRole.totalUsersCount.length /
                                    _blocRole.itemsPerPage)
                                .ceil(),
                            currentPage: _blocRole.currentPage,
                            onPageChanged: (int pageNumber) {
                              context
                                  .read<UserTableBloc>()
                                  .add(ChangePage(pageNumber));
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        } else if (state is ErrorState) {
          return Center(child: Text(state.message));
        } else {
          return const Center(child: Text('No data available.'));
        }
      },
    );
  }
}
