import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/auth/model/user_model.dart';
import 'package:syncrow_web/pages/common/bloc/project_manager.dart';
import 'package:syncrow_web/pages/roles_and_permission/model/roles_user_model.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/view/basics_view.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/view/roles_and_permission.dart';
import 'package:syncrow_web/pages/roles_and_permission/users_page/add_user_dialog/view/spaces_access_view.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';

class EditUserDialog extends StatefulWidget {
  final RolesUserModel? user;
  const EditUserDialog({
    super.key,
    this.user,
  });

  @override
  _EditUserDialogState createState() => _EditUserDialogState();
}

class _EditUserDialogState extends State<EditUserDialog> {
  int currentStep = 1;

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
        create: (BuildContext context) => UsersBloc()
          // ..add(const LoadCommunityAndSpacesEvent())
          ..add(const RoleEvent())
          ..add(GetUserByIdEvent(uuid: widget.user!.uuid)),
        child: BlocConsumer<UsersBloc, UsersState>(listener: (context, state) {
          if (state is SpacesLoadedState) {
            BlocProvider.of<UsersBloc>(context)
                .add(GetUserByIdEvent(uuid: widget.user!.uuid));
          }
        }, builder: (context, state) {
          final _blocRole = BlocProvider.of<UsersBloc>(context);

          return Dialog(
              child: Container(
            decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(20))),
            width: 900,
            child: Column(
              children: [
                // Title
                const Padding(
                  padding: EdgeInsets.all(8.0),
                  child: SizedBox(
                    child: Text(
                      "Edit User",
                      style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.w700,
                          color: ColorsManager.secondaryColor),
                    ),
                  ),
                ),
                const Divider(),
                Expanded(
                  child: Row(
                    children: [
                      Expanded(
                        child: Container(
                          padding: const EdgeInsets.all(20),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              _buildStep1Indicator(1, "Basics", _blocRole),
                              _buildStep2Indicator(2, "Spaces", _blocRole),
                              _buildStep3Indicator(
                                  3, "Role & Permissions", _blocRole),
                            ],
                          ),
                        ),
                      ),
                      Container(
                        width: 1,
                        color: ColorsManager.grayBorder,
                      ),
                      Expanded(
                        flex: 2,
                        child: Padding(
                          padding: const EdgeInsets.all(20.0),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              const SizedBox(height: 10),
                              Expanded(
                                child: _getFormContent(widget.user!),
                              ),
                              const SizedBox(height: 20),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                const Divider(),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      InkWell(
                        onTap: () {
                          Navigator.of(context).pop();
                        },
                        child: const Text("Cancel"),
                      ),
                      InkWell(
                        onTap: () {
                          // _blocRole.add(const CheckEmailEvent());

                          setState(() {
                            if (currentStep < 3) {
                              currentStep++;
                              if (currentStep == 2) {
                                _blocRole
                                    .add(CheckStepStatus(isEditUser: true));
                              } else if (currentStep == 3) {
                                _blocRole.add(const CheckSpacesStepStatus());
                              }
                            } else {
                              _blocRole.add(EditInviteUsers(
                                  context: context, userId: widget.user!.uuid));
                            }
                          });
                        },
                        child: Text(
                          currentStep < 3 ? "Next" : "Save",
                          style: TextStyle(
                              color: (_blocRole.isCompleteSpaces == false ||
                                          _blocRole.isCompleteBasics == false ||
                                          _blocRole.isCompleteRolePermissions ==
                                              false) &&
                                      currentStep == 3
                                  ? ColorsManager.grayColor
                                  : ColorsManager.secondaryColor),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ));
        }));
  }

  Widget _getFormContent(RolesUserModel user) {
    switch (currentStep) {
      case 1:
        return BasicsView(
          userId: user.uuid,
        );
      case 2:
        return SpacesAccessView(
          userId: user.uuid,
        );
      case 3:
        return const RolesAndPermission();
      default:
        return Container();
    }
  }

  int step3 = 0;

  Widget _buildStep1Indicator(int step, String label, UsersBloc bloc) {
    final isCurrentStep = currentStep == step;
    return GestureDetector(
      onTap: () {
        setState(() {
          bloc.add(const CheckSpacesStepStatus());
          currentStep = step;
          Future.delayed(const Duration(milliseconds: 500), () {
            bloc.add(ValidateBasicsStep());
          });
        });

        if (step3 == 3) {
          bloc.add(const CheckRoleStepStatus());
        }
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(5.0),
            child: Row(
              children: [
                SvgPicture.asset(
                  isCurrentStep
                      ? Assets.currentProcessIcon
                      : bloc.isCompleteBasics == false
                          ? Assets.wrongProcessIcon
                          : bloc.isCompleteBasics == true
                              ? Assets.completeProcessIcon
                              : Assets.uncomplete_ProcessIcon,
                  width: 25,
                  height: 25,
                ),
                const SizedBox(width: 10),
                Text(
                  label,
                  style: TextStyle(
                    fontSize: 16,
                    color: isCurrentStep
                        ? ColorsManager.blackColor
                        : ColorsManager.greyColor,
                    fontWeight:
                        isCurrentStep ? FontWeight.bold : FontWeight.normal,
                  ),
                ),
              ],
            ),
          ),
          if (step != 3)
            Padding(
              padding: const EdgeInsets.all(5.0),
              child: Padding(
                padding: const EdgeInsets.only(left: 12),
                child: Container(
                  height: 60,
                  width: 1,
                  color: Colors.grey,
                ),
              ),
            )
        ],
      ),
    );
  }

  Widget _buildStep2Indicator(int step, String label, UsersBloc bloc) {
    final isCurrentStep = currentStep == step;
    return GestureDetector(
      onTap: () {
        setState(() {
          currentStep = step;
          bloc.add(CheckStepStatus(isEditUser: true));
          if (step3 == 3) {
            bloc.add(const CheckRoleStepStatus());
          }
        });
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(5.0),
            child: Row(
              children: [
                SvgPicture.asset(
                  isCurrentStep
                      ? Assets.currentProcessIcon
                      : bloc.isCompleteSpaces == false
                          ? Assets.wrongProcessIcon
                          : bloc.isCompleteSpaces == true
                              ? Assets.completeProcessIcon
                              : Assets.uncomplete_ProcessIcon,
                  width: 25,
                  height: 25,
                ),
                const SizedBox(width: 10),
                Text(
                  label,
                  style: TextStyle(
                    fontSize: 16,
                    color: isCurrentStep
                        ? ColorsManager.blackColor
                        : ColorsManager.greyColor,
                    fontWeight:
                        isCurrentStep ? FontWeight.bold : FontWeight.normal,
                  ),
                ),
              ],
            ),
          ),
          if (step != 3)
            Padding(
              padding: const EdgeInsets.all(5.0),
              child: Padding(
                padding: const EdgeInsets.only(left: 12),
                child: Container(
                  height: 60,
                  width: 1,
                  color: Colors.grey,
                ),
              ),
            )
        ],
      ),
    );
  }

  Widget _buildStep3Indicator(int step, String label, UsersBloc bloc) {
    final isCurrentStep = currentStep == step;
    return GestureDetector(
      onTap: () {
        setState(() {
          currentStep = step;
          step3 = step;
          bloc.add(const CheckSpacesStepStatus());
          bloc.add(CheckStepStatus(isEditUser: true));
        });
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(5.0),
            child: Row(
              children: [
                SvgPicture.asset(
                  isCurrentStep
                      ? Assets.currentProcessIcon
                      : bloc.isCompleteRolePermissions == false
                          ? Assets.wrongProcessIcon
                          : bloc.isCompleteRolePermissions == true
                              ? Assets.completeProcessIcon
                              : Assets.uncomplete_ProcessIcon,
                  width: 25,
                  height: 25,
                ),
                const SizedBox(width: 10),
                Text(
                  label,
                  style: TextStyle(
                    fontSize: 16,
                    color: isCurrentStep
                        ? ColorsManager.blackColor
                        : ColorsManager.greyColor,
                    fontWeight:
                        isCurrentStep ? FontWeight.bold : FontWeight.normal,
                  ),
                ),
              ],
            ),
          ),
          if (step != 3)
            Padding(
              padding: const EdgeInsets.all(5.0),
              child: Padding(
                padding: const EdgeInsets.only(left: 12),
                child: Container(
                  height: 60,
                  width: 1,
                  color: Colors.grey,
                ),
              ),
            )
        ],
      ),
    );
  }
}
