import 'package:dropdown_button2/dropdown_button2.dart';
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/bloc/auth_bloc.dart';
import 'package:syncrow_web/pages/auth/bloc/auth_event.dart';
import 'package:syncrow_web/pages/auth/bloc/auth_state.dart';
import 'package:syncrow_web/pages/auth/model/region_model.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/common/first_layer.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/style.dart';

class ForgetPasswordWebPage extends StatelessWidget {
  const ForgetPasswordWebPage({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocProvider(
        create: (context) => AuthBloc()..add(RegionInitialEvent()),
        child: BlocConsumer<AuthBloc, AuthState>(
          listener: (context, state) {
            if (state is SuccessForgetState) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('Change Password Successfully '),
                ),
              );
              Navigator.of(context).pop();
            } else if (state is FailureForgetState) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(state.error),
                ),
              );
            }
          },
          builder: (context, state) {
            return _buildForm(context, state);
          },
        ),
      ),
    );
  }

  Widget _buildForm(BuildContext context, AuthState state) {
    late ScrollController _scrollController;
    _scrollController = ScrollController();
    void _scrollToCenter() {
      final double middlePosition = _scrollController.position.maxScrollExtent / 2;
      _scrollController.animateTo(
        middlePosition,
        duration: const Duration(seconds: 1),
        curve: Curves.easeInOut,
      );
    }

    WidgetsBinding.instance.addPostFrameCallback((_) {
      _scrollToCenter();
    });
    final forgetBloc = BlocProvider.of<AuthBloc>(context);
    Size size = MediaQuery.of(context).size;
    return FirstLayer(
        second: Center(
      child: Stack(
        children: [
          if (state is AuthLoading) const Center(child: CircularProgressIndicator()),
          ListView(
            shrinkWrap: true,
            controller: _scrollController,
            children: [
              Container(
                padding: EdgeInsets.all(size.width * 0.02),
                margin: EdgeInsets.all(size.width * 0.09),
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.3),
                  borderRadius: const BorderRadius.all(Radius.circular(20)),
                ),
                child: Center(
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Spacer(),
                      Expanded(
                        flex: 3,
                        child: SvgPicture.asset(
                          Assets.loginLogo,
                        ),
                      ),
                      const Spacer(),
                      Expanded(
                        flex: 3,
                        child: Container(
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.1),
                            borderRadius: const BorderRadius.all(Radius.circular(30)),
                            border: Border.all(color: ColorsManager.graysColor.withOpacity(0.2)),
                          ),
                          child: Form(
                            key: forgetBloc.forgetFormKey,
                            child: Padding(
                              padding: EdgeInsets.symmetric(
                                  horizontal: size.width * 0.02, vertical: size.width * 0.003),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: <Widget>[
                                  const SizedBox(height: 10),
                                  const Text(
                                    'Forget Password',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 24,
                                        fontWeight: FontWeight.bold),
                                  ),
                                  const SizedBox(height: 10),
                                  Text(
                                    'Please fill in your account information to\nretrieve your password',
                                    style: Theme.of(context)
                                        .textTheme
                                        .bodySmall!
                                        .copyWith(fontSize: 14, fontWeight: FontWeight.w400),
                                  ),
                                  const SizedBox(height: 10),
                                  // Column(
                                  //   crossAxisAlignment: CrossAxisAlignment.start,
                                  //   mainAxisAlignment: MainAxisAlignment.start,
                                  //   children: [
                                  // const SizedBox(height: 10),
                                  // Form(
                                  //     key: forgetBloc.forgetRegionKey,
                                  //     child: SizedBox(
                                  //         child:
                                  //             _buildDropdownField(context, forgetBloc, size)))
                                  //   ],
                                  // ),
                                  const SizedBox(height: 20),
                                  Form(
                                      key: forgetBloc.forgetEmailKey,
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        mainAxisAlignment: MainAxisAlignment.start,
                                        children: [
                                          Text(
                                            "Account",
                                            style: Theme.of(context).textTheme.bodySmall!.copyWith(
                                                fontSize: 14, fontWeight: FontWeight.w400),
                                          ),
                                          const SizedBox(height: 10),
                                          SizedBox(
                                            child: TextFormField(
                                              controller: forgetBloc.forgetEmailController,
                                              validator: forgetBloc.validateEmail,
                                              decoration: textBoxDecoration()!.copyWith(
                                                hintText: 'Enter your email',
                                                hintStyle: Theme.of(context)
                                                    .textTheme
                                                    .bodySmall!
                                                    .copyWith(
                                                        color: ColorsManager.grayColor,
                                                        fontWeight: FontWeight.w400),
                                              ),
                                              style: const TextStyle(color: Colors.black),
                                            ),
                                          ),
                                        ],
                                      )),
                                  const SizedBox(height: 20.0),
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      Text(
                                        "One Time Password",
                                        style: Theme.of(context)
                                            .textTheme
                                            .bodySmall!
                                            .copyWith(fontSize: 14, fontWeight: FontWeight.w400),
                                      ),
                                      const SizedBox(height: 10),
                                      SizedBox(
                                        child: TextFormField(
                                          validator: forgetBloc.validateCode,
                                          keyboardType: TextInputType.visiblePassword,
                                          controller: forgetBloc.forgetOtp,
                                          decoration: textBoxDecoration()!.copyWith(
                                            hintText: 'Enter Code',
                                            hintStyle: Theme.of(context)
                                                .textTheme
                                                .bodySmall!
                                                .copyWith(
                                                    color: ColorsManager.grayColor,
                                                    fontWeight: FontWeight.w400),
                                            suffixIcon: SizedBox(
                                              width: 100,
                                              child: Center(
                                                child: InkWell(
                                                  onTap: state is TimerState &&
                                                          !state.isButtonEnabled &&
                                                          state.remainingTime != 1
                                                      ? null
                                                      : 
                                                       () {
                                                          if (forgetBloc
                                                              .forgetEmailKey
                                                              .currentState!
                                                              .validate()) {
                                                            forgetBloc.add(
                                                                StartTimerEvent());
                                                          }
                                                        },
                                                
                                                  child: Text(
                                                    'Get Code ${state is TimerState && !state.isButtonEnabled && state.remainingTime != 1 ? "(${forgetBloc.formattedTime(state.remainingTime)}) " : ""}',
                                                    style: TextStyle(
                                                      color: state is TimerState &&
                                                              !state.isButtonEnabled
                                                          ? Colors.grey
                                                          : ColorsManager.btnColor,
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ),
                                          ),
                                          style: const TextStyle(color: Colors.black),
                                        ),
                                      ),
                                      if (forgetBloc.forgetValidate !=
                                          '') // Check if there is a validation message
                                        Padding(
                                          padding: const EdgeInsets.only(top: 8.0),
                                          child: Text(
                                            forgetBloc.forgetValidate,
                                            style: const TextStyle(
                                                color: ColorsManager.red,
                                                fontSize: 10,
                                                fontWeight: FontWeight.w700),
                                          ),
                                        ),
                                    ],
                                  ),
                                  const SizedBox(height: 20.0),
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      Text(
                                        "Password",
                                        style: Theme.of(context)
                                            .textTheme
                                            .bodySmall!
                                            .copyWith(fontSize: 14, fontWeight: FontWeight.w400),
                                      ),
                                      const SizedBox(height: 10),
                                      SizedBox(
                                        child: TextFormField(
                                          obscureText: forgetBloc.obscureText,
                                          keyboardType: TextInputType.visiblePassword,
                                          validator: forgetBloc.passwordValidator,
                                          controller: forgetBloc.forgetPasswordController,
                                          decoration: textBoxDecoration()!.copyWith(
                                            suffixIcon: IconButton(
                                              onPressed: () {
                                                forgetBloc.add(PasswordVisibleEvent(
                                                    newValue: forgetBloc.obscureText));
                                              },
                                              icon: SizedBox(
                                                child: SvgPicture.asset(
                                                  forgetBloc.obscureText
                                                      ? Assets.visiblePassword
                                                      : Assets.invisiblePassword,
                                                  height: 15,
                                                  width: 15,
                                                ),
                                              ),
                                            ),
                                            hintText: 'At least 8 characters',
                                            hintStyle: Theme.of(context)
                                                .textTheme
                                                .bodySmall!
                                                .copyWith(
                                                    color: ColorsManager.grayColor,
                                                    fontWeight: FontWeight.w400),
                                          ),
                                          style: const TextStyle(color: Colors.black),
                                        ),
                                      ),
                                    ],
                                  ),
                                  const SizedBox(
                                    height: 10,
                                  ),
                                  const SizedBox(height: 20.0),
                                  Row(
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      SizedBox(
                                        width: size.width * 0.2,
                                        child: DefaultButton(
                                          backgroundColor: ColorsManager.btnColor,
                                          child: const Text('Submit'),
                                          onPressed: () {
                                            if (forgetBloc.forgetFormKey.currentState!.validate() ||
                                                forgetBloc.forgetEmailKey.currentState!
                                                    .validate()) {
                                              if (forgetBloc.forgetEmailKey.currentState!
                                                      .validate() &&
                                                  forgetBloc.forgetFormKey.currentState!
                                                      .validate()) {
                                                forgetBloc.add(ChangePasswordEvent());
                                              }
                                            }
                                          },
                                        ),
                                      ),
                                    ],
                                  ),
                                  const SizedBox(height: 10.0),
                                  Center(
                                    child: SizedBox(
                                      child: Text(
                                        forgetBloc.validate,
                                        style: const TextStyle(
                                            fontWeight: FontWeight.w700, color: ColorsManager.red),
                                      ),
                                    ),
                                  ),
                                  const SizedBox(
                                    height: 10,
                                  ),
                                  SizedBox(
                                    child: Center(
                                      child: Wrap(
                                        children: [
                                          const Text(
                                            "Do you have an account? ",
                                            style: TextStyle(color: Colors.white),
                                          ),
                                          InkWell(
                                            onTap: () {
                                              forgetBloc.add(StopTimerEvent());
                                              Navigator.pop(context);
                                            },
                                            child: const Text(
                                              "Sign in",
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                  const SizedBox(height: 15.0),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                      const Spacer(),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    ));
  }

  Widget _buildDropdownField(BuildContext context, AuthBloc loginBloc, Size size) {
    final TextEditingController textEditingController = TextEditingController();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text(
          "Country/Region",
          style: Theme.of(context).textTheme.bodySmall!.copyWith(
                fontSize: 14,
                fontWeight: FontWeight.w400,
              ),
        ),
        const SizedBox(height: 10),
        SizedBox(
          width: size.width * 0.9,
          child: FormField<String>(
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please select a country/region';
              }
              return null;
            },
            builder: (FormFieldState<String> field) {
              return InputDecorator(
                decoration: InputDecoration(
                  contentPadding: const EdgeInsets.symmetric(horizontal: 2, vertical: 10),
                  errorText: field.errorText,
                  filled: true, // Ensure the dropdown is filled with the background color
                  fillColor: ColorsManager.boxColor, // Match the dropdown container color
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.0),
                    borderSide: BorderSide(
                      color: field.hasError ? Colors.red : Colors.transparent,
                      width: 1.5,
                    ),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.0),
                    borderSide: BorderSide(
                      color: field.hasError ? Colors.red : ColorsManager.grayColor,
                      width: 1.5,
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.0),
                    borderSide: BorderSide(
                      color: field.hasError ? Colors.red : ColorsManager.grayColor,
                      width: 1.5,
                    ),
                  ),
                  errorBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(8.0),
                    borderSide: const BorderSide(
                      color: Colors.red,
                      width: 1.5,
                    ),
                  ),
                ),
                child: DropdownButtonHideUnderline(
                  child: DropdownButton2<String>(
                    isExpanded: true,
                    hint: Text(
                      'Select your region/country',
                      style: Theme.of(context).textTheme.bodySmall!.copyWith(
                            color: ColorsManager.grayColor,
                            fontWeight: FontWeight.w400,
                          ),
                      overflow: TextOverflow.ellipsis,
                    ),
                    items: loginBloc.regionList!.map((RegionModel region) {
                      return DropdownMenuItem<String>(
                        value: region.id,
                        child: Text(
                          style: Theme.of(context).textTheme.bodyMedium!.copyWith(
                                fontSize: 14,
                                fontWeight: FontWeight.w400,
                              ),
                          region.name,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                        ),
                      );
                    }).toList(),
                    // value: loginBloc.regionList!.any((region) => region.id == loginBloc.regionUuid)
                    //     ? loginBloc.regionUuid
                    //     : null,
                    onChanged: (String? value) {
                      if (value != null) {
                        loginBloc.add(SelectRegionEvent(val: value));
                        field.didChange(value); // Notify the form field of the change
                      }
                    },
                    buttonStyleData: const ButtonStyleData(
                      padding: EdgeInsets.symmetric(horizontal: 16),
                      height: 40,
                      width: double.infinity,
                    ),
                    dropdownStyleData: DropdownStyleData(
                      maxHeight: size.height * 0.70,
                      decoration: BoxDecoration(
                        color: ColorsManager
                            .boxColor, // Match dropdown background color to the container
                        borderRadius: BorderRadius.circular(8.0),
                      ),
                    ),
                    menuItemStyleData: const MenuItemStyleData(
                      height: 40,
                    ),
                    dropdownSearchData: DropdownSearchData(
                      searchController: textEditingController,
                      searchInnerWidgetHeight: 50,
                      searchInnerWidget: Container(
                        height: 50,
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        child: TextFormField(
                          style: const TextStyle(color: Colors.black),
                          controller: textEditingController,
                          decoration: textBoxDecoration()!.copyWith(
                            errorStyle: const TextStyle(height: 0),
                            contentPadding: const EdgeInsets.symmetric(
                              vertical: 12,
                              horizontal: 10,
                            ),
                          ),
                        ),
                      ),
                      searchMatchFn: (item, searchValue) {
                        final regionName = (item.child as Text).data?.toLowerCase() ?? '';
                        final search = searchValue.toLowerCase().trim();
                        return regionName.contains(search);
                      },
                    ),
                    onMenuStateChange: (isOpen) {
                      if (!isOpen) {
                        textEditingController.clear();
                      }
                    },
                  ),
                ),
              );
            },
          ),
        ),
      ],
    );
  }
}
