import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hoshan/data/model/auth/auth_screens_enum.dart';
import 'package:hoshan/ui/screens/auth/cubit/auth_screens_cubit.dart';
import 'package:hoshan/ui/screens/auth/register/bloc/register_bloc.dart';
import 'package:hoshan/ui/screens/auth/verification/verification_screen.dart';
import 'package:hoshan/ui/theme/colors.dart';
import 'package:hoshan/ui/theme/text.dart';
import 'package:hoshan/ui/widgets/components/button/loading_button.dart';
import 'package:hoshan/ui/widgets/components/text/mobile_number_text_field.dart';
import 'package:persian_number_utility/persian_number_utility.dart';
import 'package:string_validator/string_validator.dart';

class RegisterScreen extends StatefulWidget {
  const RegisterScreen({super.key});

  @override
  State<RegisterScreen> createState() => _RegisterScreenState();
}

class _RegisterScreenState extends State<RegisterScreen> {
  final TextEditingController number = TextEditingController();
  final ValueNotifier<bool> error = ValueNotifier(false);
  bool canSend = false;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // Text(
        //   '.شماره همراه یا ایمیل خود را وارد کنید',
        //   style: AppTextStyles.body4.copyWith(
        //       fontWeight: FontWeight.bold,
        //       color: Theme.of(context).colorScheme.onSurface),
        // ),
        BlocConsumer<RegisterBloc, RegisterState>(
          listener: (context, state) {
            if (state is RegisterSuccess) {
              context.read<AuthScreensCubit>().username = number.text;
              context.read<AuthScreensCubit>().isNew = state.isNew;
              context
                  .read<AuthScreensCubit>()
                  .changeState(AuthScreens.verification);
            }
            if (state is RegisterFail) {
              if (state.statusCode == 429 && state.error != null) {
                seconds.value =
                    int.tryParse(state.error!.replaceAll(RegExp(r'\D'), '')) ??
                        120;
                context.read<AuthScreensCubit>().username = number.text;

                context
                    .read<AuthScreensCubit>()
                    .changeState(AuthScreens.verification);
                error.value = false;

                return;
              }
              error.value = true;
            }
          },
          builder: (context, state) {
            return Column(
              children: [
                Padding(
                  padding: const EdgeInsets.all(18.0),
                  child: Directionality(
                    textDirection: TextDirection.rtl,
                    child: ValueListenableBuilder(
                        valueListenable: error,
                        builder: (context, errVal, _) {
                          return MobileNumberTextField(
                            controller: number,
                            onChange: (val) {
                              setState(() {
                                val = val.toEnglishDigit();
                                canSend = val.length == 11 && isNumeric(val);
                              });
                            },
                            // maxLength: 11,
                            label: 'شماره همراه',
                            // suffix: const Icon(CupertinoIcons.phone),
                            error: errVal
                                ? Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Icon(
                                        Icons.warning_amber_rounded,
                                        color: AppColors.red.defaultShade,
                                        size: 16,
                                      ),
                                      const SizedBox(
                                        width: 8,
                                      ),
                                      Expanded(
                                        child: Text(
                                          (state as RegisterFail).error ?? '',
                                          style: AppTextStyles.body5.copyWith(
                                              color:
                                                  AppColors.red.defaultShade),
                                        ),
                                      ),
                                    ],
                                  )
                                : null,
                          );
                        }),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16.0),
                  child: LoadingButton(
                      width: MediaQuery.sizeOf(context).width,
                      height: 48,
                      radius: 100,
                      loading: state is RegisterLoading,
                      onPressed: canSend
                          ? () {
                              context.read<RegisterBloc>().add(LoginUser(
                                  phoneNumber: number.text.toEnglishDigit()));
                            }
                          : null,
                      child: Text(
                        'ارسال کد',
                        style: AppTextStyles.body4.copyWith(
                            color: canSend
                                ? Colors.white
                                : Color.fromARGB(255, 112, 112, 110)),
                      )),
                ),
              ],
            );
          },
        ),
      ],
    );
  }
}
