import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.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 AddNewUserDialog extends StatefulWidget {
  const AddNewUserDialog({super.key});

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

class _AddNewUserDialogState extends State<AddNewUserDialog> {
  int currentStep = 1;

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
        create: (BuildContext context) => UsersBloc()
          // ..add(const LoadCommunityAndSpacesEvent())
          ..add(const RoleEvent()),
        child: BlocConsumer<UsersBloc, UsersState>(
            listener: (context, state) {},
            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(
                          "Add New 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(),
                                  ),
                                  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: () {
                              final isBasicsStep = currentStep == 1;

                              if (isBasicsStep) {
                                // Validate the form first
                                final isValid = _blocRole.formKey.currentState
                                        ?.validate() ??
                                    false;

                                if (!isValid)
                                  return; // Stop if form is not valid
                              }
                              _blocRole.add(const CheckEmailEvent());

                              setState(() {
                                if (currentStep < 3) {
                                  currentStep++;
                                  if (currentStep == 2) {
                                    _blocRole.add(const CheckStepStatus(
                                        isEditUser: false));
                                  } else if (currentStep == 3) {
                                    _blocRole
                                        .add(const CheckSpacesStepStatus());
                                  }
                                } else {
                                  _blocRole
                                      .add(SendInviteUsers(context: context));
                                }
                              });
                            },
                            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() {
    switch (currentStep) {
      case 1:
        return BasicsView(
          userId: '',
        );
      case 2:
        return const SpacesAccessView();
      case 3:
        return const RolesAndPermission();
      default:
        return Container();
    }
  }

  int step3 = 0;

  Widget _buildStep1Indicator(int step, String label, UsersBloc bloc) {
    return GestureDetector(
      onTap: () {
        setState(() {
          bloc.add(const CheckSpacesStepStatus());
          currentStep = step;
          Future.delayed(const Duration(milliseconds: 500), () {
            bloc.add(const 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(
                  currentStep == step
                      ? 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: currentStep == step
                        ? ColorsManager.blackColor
                        : ColorsManager.greyColor,
                    fontWeight: currentStep == step
                        ? 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) {
    return GestureDetector(
      onTap: () {
        setState(() {
          bloc.add(const CheckStepStatus(isEditUser: false));
          currentStep = step;
          Future.delayed(const Duration(milliseconds: 500), () {
            bloc.add(const CheckStepStatus(isEditUser: false));
          });
          if (step3 == 3) {
            Future.delayed(const Duration(seconds: 1), () {
              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(
                  currentStep == step
                      ? 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: currentStep == step
                        ? ColorsManager.blackColor
                        : ColorsManager.greyColor,
                    fontWeight: currentStep == step
                        ? 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) {
    return GestureDetector(
      onTap: () {
        setState(() {
          currentStep = step;
          step3 = step;
          bloc.add(const CheckSpacesStepStatus());
          bloc.add(CheckStepStatus(isEditUser: false));
        });
      },
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(5.0),
            child: Row(
              children: [
                SvgPicture.asset(
                  currentStep == step
                      ? 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: currentStep == step
                        ? ColorsManager.blackColor
                        : ColorsManager.greyColor,
                    fontWeight: currentStep == step
                        ? 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,
                ),
              ),
            )
        ],
      ),
    );
  }
}
