import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/src/widgets/placeholder.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:group_list_view/group_list_view.dart';
import 'package:multi_dropdown/models/value_item.dart';
import 'package:multi_dropdown/multiselect_dropdown.dart';
import 'package:unit2/bloc/role/pass_check/est_point_person/est_point_person_role_assignment/est_role_assignment_bloc.dart';
import 'package:unit2/bloc/role/pass_check/est_point_person/est_point_person_station/est_point_person_station_bloc.dart';
import 'package:unit2/bloc/role_assignment/role_assignment_bloc.dart';
import 'package:unit2/theme-data.dart/form-style.dart';
import 'package:unit2/widgets/Leadings/add_leading.dart';
import 'package:unit2/widgets/empty_data.dart';
import 'package:unit2/widgets/error_state.dart';

import '../../../../model/rbac/assigned_role.dart';
import '../../../../model/rbac/rbac.dart';
import '../../../../theme-data.dart/btn-style.dart';
import '../../../../theme-data.dart/colors.dart';
import '../../../../utils/alerts.dart';
import '../../../../utils/global_context.dart';

class EstPointPersonRoleAssignmentScreen extends StatelessWidget {
  final int id;
  const EstPointPersonRoleAssignmentScreen({super.key, required this.id});

  @override
  Widget build(BuildContext context) {
    Map<String, List<Content>> assignedRoles = {};
    List<AssignedRole> roles = [];
    List<ValueItem> valueItemAssignableRoles = [];
    List<ValueItem> selectedValueItemAssignableRoles = [];
    List<RBAC> assignabledRoles = [];
    List<Content> users = [];
    List<int> userIds = [];
    int? selectedUserId;
    final formKey = GlobalKey<FormBuilderState>();
    final parent = context;
    return Scaffold(
      appBar: AppBar(
        title: const Text("Role Members"),
        backgroundColor: primary,
        actions: [
          AddLeading(onPressed: () {
            for (var role in roles) {
              String fullname =
                  "${role.user!.firstName} ${role.user!.lastName}";
              if (!userIds.contains(role.user!.id)) {
                userIds.add(role.user!.id);
                users.add(Content(id: role.user!.id, name: fullname));
              }
            }
            showDialog(
                context: NavigationService.navigatorKey.currentState!.context,
                builder: (context) {
                  valueItemAssignableRoles = assignabledRoles.map((e) {
                    return ValueItem(label: e.name!, value: e.id.toString());
                  }).toList();
                  return AlertDialog(
                    title: const Text("Assign Role to User"),
                    content: FormBuilder(
                        key: formKey,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            FormBuilderDropdown(
                                decoration: normalTextFieldStyle(
                                    "Select Person", "Select Person"),
                                name: 'users',
                                onChanged: (value) {
                                  selectedUserId = value!.id;
                                },
                                items: users.map((e) {
                                  return DropdownMenuItem(
                                    value: e,
                                    child: Text(e.name),
                                  );
                                }).toList()),
                            const SizedBox(
                              height: 12,
                            ),
                            MultiSelectDropDown(
                              onOptionSelected:
                                  (List<ValueItem> selectedOptions) {
                                selectedValueItemAssignableRoles =
                                    selectedOptions;
                              },
                              borderColor: Colors.grey,
                              borderWidth: 1,
                              borderRadius: 5,
                              hint: "Select Roles",
                              padding: const EdgeInsets.all(8),
                              options: valueItemAssignableRoles,
                              selectionType: SelectionType.multi,
                              chipConfig:
                                  const ChipConfig(wrapType: WrapType.wrap),
                              dropdownHeight: 300,
                              optionTextStyle: const TextStyle(fontSize: 16),
                              selectedOptionIcon:
                                  const Icon(Icons.check_circle),
                            ),
                            const SizedBox(
                              height: 12,
                            ),
                            SizedBox(
                                width: double.infinity,
                                height: 50,
                                child: ElevatedButton(
                                    style: mainBtnStyle(
                                        primary, Colors.transparent, second),
                                    onPressed: () {
                                      if (formKey.currentState!
                                          .saveAndValidate()) {
                                        List<int> rolesId = [];
                                        for (var role in assignabledRoles) {
                                          selectedValueItemAssignableRoles
                                              .forEach((element) {
                                            if (element.value ==
                                                role.id.toString()) {
                                              rolesId.add(role.id!);
                                            }
                                          });
                                        }
                                        parent
                                            .read<EstRoleAssignmentBloc>()
                                            .add(EstPointPersonAssignRole(
                                                rolesId: rolesId,
                                                assingerId: id,
                                                userId: selectedUserId!));
                                        Navigator.pop(context);
                                      }
                                    },
                                    child: const Text("Add"))),
                          ],
                        )),
                  );
                });
          })
        ],
      ),
      body: ProgressHUD(
        padding: const EdgeInsets.all(24),
        backgroundColor: Colors.black87,
        indicatorWidget: const SpinKitFadingCircle(color: Colors.white),
        child: BlocConsumer<EstRoleAssignmentBloc, EstRoleAssignmentState>(
            builder: (context, state) {
          if (state is EstPointPersonRolesUnderLoadedState) {
            roles = state.assignedRoles;
            assignabledRoles = state.assignableRole;
            assignedRoles = {};
            if (state.assignedRoles.isNotEmpty) {
              for (var assignedRole in state.assignedRoles) {
                String? fullName =
                    "${assignedRole.user!.firstName} ${assignedRole.user!.lastName}";
                if (!assignedRoles.keys.contains(fullName)) {
                  assignedRoles.addAll({fullName: []});
                  assignedRoles[fullName]!.add(Content(
                      id: assignedRole.id!, name: assignedRole.role!.name));
                } else {
                  assignedRoles[fullName]!.add(Content(
                      id: assignedRole.id!,
                      name: assignedRole.role!.name));
                }
              }
            }
            if (state.assignedRoles.isNotEmpty) {
              return GroupListView(
                sectionsCount: assignedRoles.keys.toList().length,
                countOfItemInSection: (int section) {
                  return assignedRoles.values.toList()[section].length;
                },
                separatorBuilder: (context, index) {
                  return const Divider();
                },
                itemBuilder: (BuildContext context, IndexPath index) {
                  return ListTile(
                    trailing: IconButton(
                      color: Colors.grey.shade600,
                      icon: const Icon(Icons.delete),
                      onPressed: () {
                        confirmAlert(context, () {
                          context.read<EstRoleAssignmentBloc>().add(
                              EstPointPersonDeleteAssignRole(
                                  roleId: assignedRoles.values
                                      .toList()[index.section][index.index]
                                      .id));
                        }, "Delete?", "Confirm Delete?");
                      },
                    ),
                    title: Row(
                      children: [
                        CircleAvatar(
                            child: Text("${index.index + 1}",
                                style: Theme.of(context)
                                    .textTheme
                                    .labelLarge!
                                    .copyWith(color: Colors.white))),
                        const SizedBox(
                          width: 20,
                        ),
                        Expanded(
                          child: Text(
                            assignedRoles.values
                                .toList()[index.section][index.index]
                                .name
                                .toUpperCase(),
                            style: Theme.of(context)
                                .textTheme
                                .labelLarge!
                                .copyWith(
                                    fontWeight: FontWeight.w600,
                                    color: primary),
                          ),
                        ),
                      ],
                    ),
                  );
                },
                groupHeaderBuilder: (BuildContext context, int section) {
                  return ListTile(
                    tileColor: second,
                    title: Text(
                      assignedRoles.keys.toList()[section].toUpperCase(),
                      style: Theme.of(context)
                          .textTheme
                          .titleMedium!
                          .copyWith(color: Colors.white),
                    ),
                  );
                },
              );
            } else {
              return const EmptyData(message: "Empty");
            }
          }
          if (state is EstPointPersonRolesUnderErrorState) {
            return SomethingWentWrong(
                message: "something went wrong. Please try again!",
                onpressed: () {});
          }
          return Container();
        }, listener: (context, state) {
          if (state is EstPointPersonRoleLoadingState) {
            final progress = ProgressHUD.of(context);
            progress!.showWithText("Please wait...");
          }
          ////Added State
          if (state is EstPointPersonRoleUnderAddedState) {
            if (state.response['success']) {
              successAlert(
                  context, "Adding Successfull!", state.response['message'],
                  () {
                Navigator.of(context).pop();
                context
                    .read<EstRoleAssignmentBloc>()
                    .add(GetEstPointPersonRolesUnder(userId: id));
              });
            } else {
              errorAlert(context, "Adding Failed", state.response['message'],
                  () {
                Navigator.of(context).pop();
                context
                    .read<EstRoleAssignmentBloc>()
                    .add(GetEstPointPersonRolesUnder(userId: id));
              });
            }
          }
          ////Deleted State
          if (state is EstPointPersonDeletedState) {
            if (state.success) {
              successAlert(
                  context, "Delete Successfull!", "Role Deleted Successfully",
                  () {
                Navigator.of(context).pop();
                context
                    .read<EstRoleAssignmentBloc>()
                    .add(GetEstPointPersonRolesUnder(userId: id));
              });
            } else {
              errorAlert(context, "Delete Failed", "Role Delete Failed", () {
                Navigator.of(context).pop();
                context
                    .read<EstRoleAssignmentBloc>()
                    .add(GetEstPointPersonRolesUnder(userId: id));
              });
            }
          }
          if (state is EstPointPersonRolesUnderLoadedState ||
              state is EstPointPersonRoleUnderAddedState ||
              state is EstPointPersonRoleLoadingState) {
            final progress = ProgressHUD.of(context);
            progress!.dismiss();
          }
        }),
      ),
    );
  }
}

class Content {
  final int id;
  final String name;
  const Content({required this.id, required this.name});
}
