import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/svg.dart';
import 'package:syncrow_app/features/auth/bloc/auth_cubit.dart';
import 'package:syncrow_app/features/menu/view/widgets/securty/bloc/security_bloc.dart';
import 'package:syncrow_app/features/menu/view/widgets/securty/bloc/security_event.dart';
import 'package:syncrow_app/features/menu/view/widgets/securty/bloc/security_state.dart';
import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_large.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_medium.dart';
import 'package:syncrow_app/generated/assets.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';

class SetPasswordPage extends StatelessWidget {
  String? otpCode;
  SetPasswordPage({super.key, this.otpCode});

  @override
  Widget build(BuildContext context) {
    final _formKey = GlobalKey<FormState>();

    return BlocProvider<SecurityBloc>(
        create: (context) => SecurityBloc(),
        child: Form(
            key: _formKey,
            child: BlocConsumer<SecurityBloc, SecurityState>(
                listener: (context, state) {
              if (state is SuccessForgetState) {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('Change Password Successfully '),
                  ),
                );
                Navigator.of(context).pop();
              }
              if (state is ChangedPassState) {
                showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (context) {
                    return AlertDialog(
                      contentPadding: EdgeInsets.zero,
                      content: SizedBox(
                        height: MediaQuery.of(context).size.height * 0.2,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            const SizedBox(
                              height: 10,
                            ),
                            BodyLarge(
                              text: 'Password Changed',
                              fontWeight: FontWeight.w700,
                              fontColor:
                                  ColorsManager.switchButton.withOpacity(0.6),
                              fontSize: 16,
                            ),
                            const Padding(
                              padding: EdgeInsets.only(left: 15, right: 15),
                              child: Divider(
                                color: ColorsManager.textGray,
                              ),
                            ),
                            const Padding(
                              padding: EdgeInsets.only(
                                  left: 15, right: 20, top: 15, bottom: 20),
                              child: Column(
                                children: [
                                  Center(
                                      child: Text(
                                    'Your password has been',
                                    textAlign: TextAlign.center,
                                  )),
                                  Center(
                                      child: Text(
                                    'successfully updated.',
                                    textAlign: TextAlign.center,
                                  )),
                                ],
                              ),
                            ),
                            Expanded(
                              child: Container(
                                decoration: const BoxDecoration(
                                    border: Border(
                                  top: BorderSide(
                                    color: ColorsManager.textGray,
                                    width: 1.0,
                                  ),
                                )),
                                child: InkWell(
                                    onTap: () {
                                      AuthCubit.get(context).logout();
                                    },
                                    child: Padding(
                                      padding: const EdgeInsets.only(
                                          top: 5, bottom: 5),
                                      child: Center(
                                        child: Text(
                                          'Done',
                                          style: TextStyle(
                                              color: ColorsManager.switchButton
                                                  .withOpacity(0.6),
                                              fontSize: 14,
                                              fontWeight: FontWeight.w400),
                                        ),
                                      ),
                                    )),
                              ),
                            )
                          ],
                        ),
                      ),
                    );
                  },
                );
              }
            }, builder: (context, state) {
              final _bloc = BlocProvider.of<SecurityBloc>(context);

              return DefaultScaffold(
                title: 'Change Password',
                child: ListView(
                  shrinkWrap: true,
                  children: [
                    const SizedBox(height: 55),
                    const Center(
                      child: Padding(
                        padding: EdgeInsets.all(8.0),
                        child: BodyMedium(
                          text: 'Set Password',
                          fontWeight: FontWeight.w700,
                          fontSize: 18,
                        ),
                      ),
                    ),
                    const Center(
                      child: BodyMedium(
                        text: 'Secure your account with a',
                        fontWeight: FontWeight.w400,
                        fontSize: 16,
                      ),
                    ),
                    const SizedBox(height: 4),
                    const Center(
                      child: BodyMedium(
                        text: 'strong password',
                        fontWeight: FontWeight.w400,
                        fontSize: 14,
                      ),
                    ),
                    const SizedBox(height: 40),
                    BlocBuilder<SecurityBloc, SecurityState>(
                      builder: (context, state) {
                        if (state is PasswordErrorState) {
                          return Center(
                            child: Text(
                              state.error,
                              style: const TextStyle(color: Colors.red),
                            ),
                          );
                        } else if (state is PasswordSetState) {
                          return Center(
                            child: Text(
                              state.message,
                              style: const TextStyle(color: Colors.green),
                            ),
                          );
                        }
                        return const SizedBox.shrink();
                      },
                    ),
                    PasswordInputField(
                      controller: _bloc.newPassword,
                      validatorl: _bloc.passwordValidator,
                    ),
                    const SizedBox(height: 55),
                    InkWell(
                      onTap: () {
                        if (_formKey.currentState!.validate()) {
                          _bloc.add(
                              ChangePasswordEvent(otpCode: otpCode.toString()));
                        }
                      },
                      child: Container(
                        padding: const EdgeInsets.only(
                            right: 20, left: 20, top: 15, bottom: 15),
                        decoration: const BoxDecoration(
                          color: ColorsManager.blueColor,
                          borderRadius: BorderRadius.all(Radius.circular(20)),
                        ),
                        child: const Center(
                          child: Text(
                            "Done",
                            style: TextStyle(
                              fontSize: 16,
                              color: Colors.white,
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              );
            })));
  }
}

class PasswordInputField extends StatelessWidget {
  PasswordInputField({this.controller, this.validatorl});
  TextEditingController? controller = TextEditingController();
  String? Function(String?)? validatorl;
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<SecurityBloc, SecurityState>(
      builder: (context, state) {
        bool isPasswordVisible = false;
        if (state is PasswordVisibilityState) {
          isPasswordVisible = state.isVisible;
        }

        return TextFormField(
          controller: controller,
          obscureText: !isPasswordVisible,
          validator: validatorl,
          decoration: InputDecoration(
            hintText: 'Password',
            suffixIcon: IconButton(
              icon: SvgPicture.asset(isPasswordVisible
                  ? Assets.passwordVisibility
                  : Assets.passwordUnvisibility),
              onPressed: () {
                context.read<SecurityBloc>().add(TogglePasswordVisibility());
              },
            ),
          ),
        );
      },
    );
  }

  void dispose() {
    controller!.dispose();
  }
}
