import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl_phone_field/countries.dart';
import 'package:intl_phone_field/country_picker_dialog.dart';
import 'package:intl_phone_field/intl_phone_field.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/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
import 'package:syncrow_web/utils/style.dart';

class BasicsView extends StatelessWidget {
  final String? userId;
  Timer? _debounce;

  BasicsView({super.key, this.userId = ''});
  @override
  Widget build(BuildContext context) {
    return BlocBuilder<UsersBloc, UsersState>(builder: (context, state) {
      final _blocRole = BlocProvider.of<UsersBloc>(context);
      if (state is BasicsStepInvalidState) {
        _blocRole.formKey.currentState?.validate();
      }
      return Form(
        key: _blocRole.formKey,
        autovalidateMode: AutovalidateMode.onUserInteraction,
        child: ListView(
          shrinkWrap: true,
          children: [
            Text(
              'Set up the basics',
              style: context.textTheme.bodyLarge?.copyWith(
                  fontWeight: FontWeight.w700,
                  fontSize: 20,
                  color: Colors.black),
            ),
            const SizedBox(
              height: 50,
            ),
            Text(
              'To get started, fill out some basic information about who you’re adding as a user.',
              style: context.textTheme.bodyMedium?.copyWith(
                fontWeight: FontWeight.w400,
                fontSize: 14,
              ),
            ),
            const SizedBox(
              height: 35,
            ),
            Row(
              children: [
                Flexible(
                  child: SizedBox(
                    // width: MediaQuery.of(context).size.width * 0.18,
                    height: MediaQuery.of(context).size.width * 0.08,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                            child: Row(
                          children: [
                            const Text(
                              " * ",
                              style: TextStyle(
                                color: ColorsManager.red,
                                fontWeight: FontWeight.w900,
                                fontSize: 15,
                              ),
                            ),
                            Text(
                              'First Name',
                              style: context.textTheme.bodyMedium?.copyWith(
                                fontWeight: FontWeight.w400,
                                fontSize: 13,
                              ),
                            ),
                          ],
                        )),
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: TextFormField(
                            style: const TextStyle(
                                color: ColorsManager.blackColor),
                            // onChanged: (value) {
                            //   Future.delayed(const Duration(milliseconds: 200),
                            //       () {
                            //     _blocRole.add(const ValidateBasicsStep());
                            //   });
                            // },
                            controller: _blocRole.firstNameController,
                            decoration: inputTextFormDeco(
                              hintText: "Enter first name",
                            ).copyWith(
                              hintStyle: context.textTheme.bodyMedium?.copyWith(
                                  fontWeight: FontWeight.w400,
                                  fontSize: 12,
                                  color: ColorsManager.textGray),
                            ),
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return 'Enter first name';
                              }
                              return null;
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                const SizedBox(width: 10),
                Flexible(
                  child: SizedBox(
                    // width: MediaQuery.of(context).size.width * 0.18,
                    height: MediaQuery.of(context).size.width * 0.08,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                            child: Row(
                          children: [
                            const Text(
                              " * ",
                              style: TextStyle(
                                color: ColorsManager.red,
                                fontWeight: FontWeight.w900,
                                fontSize: 15,
                              ),
                            ),
                            Text('Last Name',
                                style: context.textTheme.bodyMedium?.copyWith(
                                  fontWeight: FontWeight.w400,
                                  fontSize: 13,
                                )),
                          ],
                        )),
                        Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: TextFormField(
                            // onChanged: (value) {
                            //   Future.delayed(const Duration(milliseconds: 200),
                            //       () {
                            //     _blocRole.add(ValidateBasicsStep());
                            //   });
                            // },
                            controller: _blocRole.lastNameController,
                            style: const TextStyle(color: Colors.black),
                            decoration:
                                inputTextFormDeco(hintText: "Enter last name")
                                    .copyWith(
                                        hintStyle: context.textTheme.bodyMedium
                                            ?.copyWith(
                                                fontWeight: FontWeight.w400,
                                                fontSize: 12,
                                                color: ColorsManager.textGray)),
                            validator: (value) {
                              if (value == null || value.isEmpty) {
                                return 'Enter last name';
                              }
                              return null;
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 10),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(
                    child: Row(
                  children: [
                    const Text(
                      " * ",
                      style: TextStyle(
                        color: ColorsManager.red,
                        fontWeight: FontWeight.w900,
                        fontSize: 15,
                      ),
                    ),
                    Text(
                      'Email Address',
                      style: context.textTheme.bodyMedium?.copyWith(
                        fontWeight: FontWeight.w400,
                        fontSize: 13,
                      ),
                    ),
                  ],
                )),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: TextFormField(
                    enabled: userId != '' ? false : true,
                    // onChanged: (value) {
                    //   Future.delayed(const Duration(milliseconds: 200), () {
                    //     _blocRole.add(CheckStepStatus(
                    //         isEditUser: userId != '' ? false : true));
                    //     _blocRole.add(ValidateBasicsStep());
                    //   });
                    // },
                    controller: _blocRole.emailController,
                    style: const TextStyle(color: ColorsManager.blackColor),
                    decoration: inputTextFormDeco(hintText: "name@example.com")
                        .copyWith(
                      hintStyle: context.textTheme.bodyMedium?.copyWith(
                          fontWeight: FontWeight.w400,
                          fontSize: 12,
                          color: ColorsManager.textGray),
                    ),

                    onChanged: (value) {
                      if (_debounce?.isActive ?? false) _debounce!.cancel();
                      _debounce = Timer(const Duration(milliseconds: 800), () {
                        _blocRole.add(const CheckEmailEvent());
                      });
                    },

                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Enter Email Address';
                      }
                      final emailRegex = RegExp(
                        r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
                      );
                      if (!emailRegex.hasMatch(value)) {
                        return 'Enter a valid Email Address';
                      }
                      if (_blocRole.checkEmailValid != "Valid email") {
                        return _blocRole.checkEmailValid;
                      }
                      // return null;
                    },
                  ),
                ),
              ],
            ),
            const SizedBox(height: 10),
            Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                          child: Row(
                        children: [
                          Text(
                            'Mobile Number',
                            style: context.textTheme.bodyMedium?.copyWith(
                              fontWeight: FontWeight.w400,
                              fontSize: 13,
                            ),
                          ),
                        ],
                      )),
                      IntlPhoneField(
                        pickerDialogStyle: PickerDialogStyle(),
                        dropdownIconPosition: IconPosition.leading,
                        disableLengthCheck: true,
                        dropdownTextStyle:
                            const TextStyle(color: ColorsManager.blackColor),
                        textInputAction: TextInputAction.done,
                        decoration: inputTextFormDeco(
                          hintText: "05x xxx xxxx",
                        ).copyWith(
                          hintStyle: context.textTheme.bodyMedium?.copyWith(
                              fontWeight: FontWeight.w400,
                              fontSize: 12,
                              color: ColorsManager.textGray),
                        ),
                        initialCountryCode: 'AE',
                        countries: const [
                          Country(
                            name: "United Arab Emirates",
                            nameTranslations: {
                              "en": "United Arab Emirates",
                              "ar": "الإمارات العربية المتحدة",
                            },
                            flag: "🇦🇪",
                            code: "AE",
                            dialCode: "971",
                            minLength: 9,
                            maxLength: 9,
                          ),
                          Country(
                            name: "Saudi Arabia",
                            nameTranslations: {
                              "en": "Saudi Arabia",
                              "ar": "السعودية",
                            },
                            flag: "🇸🇦",
                            code: "SA",
                            dialCode: "966",
                            minLength: 9,
                            maxLength: 9,
                          ),
                        ],
                        style: const TextStyle(color: Colors.black),
                        controller: _blocRole.phoneController,
                      )
                    ],
                  ),
                ),
                const SizedBox(width: 10),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                          child: Row(
                        children: [
                          Text(
                            'Job Title',
                            style: context.textTheme.bodyMedium?.copyWith(
                              fontWeight: FontWeight.w400,
                              fontSize: 13,
                            ),
                          ),
                        ],
                      )),
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: TextFormField(
                          controller: _blocRole.jobTitleController,
                          style:
                              const TextStyle(color: ColorsManager.blackColor),
                          decoration: inputTextFormDeco(
                                  hintText: "Job Title (Optional)")
                              .copyWith(
                            hintStyle: context.textTheme.bodyMedium?.copyWith(
                                fontWeight: FontWeight.w400,
                                fontSize: 12,
                                color: ColorsManager.textGray),
                          ),
                          keyboardType: TextInputType.phone,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 20),
          ],
        ),
      );
    });
  }
}
