import 'package:flutter/material.dart';
import 'package:flutter_remix/flutter_remix.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:venderfoodyman/infrastructure/models/data/user_data.dart';
import 'package:venderfoodyman/presentation/component/components.dart';
import '../../../application/profile/profile_provider.dart';
import '../../../application/sign_up/sign_up_provider.dart';
import '../../../infrastructure/services/services.dart';
import '../../component/text_fields/outline_bordered_text_field.dart';
import '../../styles/style.dart';
import 'register_confirmation_page.dart';

class RegisterPage extends ConsumerWidget {
  final bool isOnlyEmail;

  const RegisterPage({
    Key? key,
    required this.isOnlyEmail,
  }) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final event = ref.read(signUpProvider.notifier);
    final state = ref.watch(signUpProvider);
    final bool isDarkMode = LocalStorage.instance.getAppThemeMode();
    final bool isLtr = LocalStorage.instance.getLangLtr();
    return Directionality(
      textDirection: isLtr ? TextDirection.ltr : TextDirection.rtl,
      child: KeyboardDisable(
        child: Container(
          margin: MediaQuery.of(context).viewInsets,
          decoration: BoxDecoration(
              color: Style.greyColor.withOpacity(0.96),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(16.r),
                topRight: Radius.circular(16.r),
              )),
          width: double.infinity,
          child: Padding(
            padding: REdgeInsets.all(16.0),
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Column(
                    children: [
                      AppBarBottomSheet(
                        title: AppHelpers.trans(TrKeys.register),
                      ),
                      isOnlyEmail
                          ? OutlinedBorderTextField(
                              label: AppHelpers.trans(TrKeys.emailOrPhone)
                                  .toUpperCase(),
                              onChanged: (value) {
                                event.setPhone(value);
                                ref
                                    .read(profileProvider.notifier)
                                    .setPhone(value);
                              },
                              isError: state.isPhoneInvalid,
                              descriptionText: state.isPhoneInvalid
                                  ? AppHelpers.trans(TrKeys.cannotBeEmpty)
                                  : null,
                            )
                          : const SizedBox.shrink(),
                      isOnlyEmail
                          ? const SizedBox.shrink()
                          : Column(
                              children: [
                                (state.verificationId.isNotEmpty)
                                    ? 30.verticalSpace
                                    : 0.verticalSpace,
                                (state.verificationId.isNotEmpty)
                                    ? OutlinedBorderTextField(
                                        label: AppHelpers.trans(TrKeys.email)
                                            .toUpperCase(),
                                        onChanged: event.setEmail,
                                        isError: state.isEmailInvalid,
                                        descriptionText: state.isEmailInvalid
                                            ? AppHelpers.trans(
                                                TrKeys.cannotBeEmpty)
                                            : null,
                                      )
                                    : const SizedBox.shrink(),
                                30.verticalSpace,
                                Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    SizedBox(
                                      width: (MediaQuery.sizeOf(context).width -
                                              40) /
                                          2,
                                      child: OutlinedBorderTextField(
                                        label:
                                            AppHelpers.trans(TrKeys.firstname)
                                                .toUpperCase(),
                                        onChanged: (name) =>
                                            event.setFirstName(name),
                                        isError: state.isFirstNameInvalid,
                                        descriptionText:
                                            state.isFirstNameInvalid
                                                ? AppHelpers.trans(
                                                    TrKeys.cannotBeEmpty)
                                                : null,
                                      ),
                                    ),
                                    SizedBox(
                                      width: (MediaQuery.sizeOf(context).width -
                                              40) /
                                          2,
                                      child: OutlinedBorderTextField(
                                        label: AppHelpers.trans(TrKeys.surname)
                                            .toUpperCase(),
                                        onChanged: (name) =>
                                            event.setLatName(name),
                                        isError: state.isSurNameInvalid,
                                        descriptionText: state.isSurNameInvalid
                                            ? AppHelpers.trans(
                                                TrKeys.cannotBeEmpty)
                                            : null,
                                      ),
                                    ),
                                  ],
                                ),
                                30.verticalSpace,
                                OutlinedBorderTextField(
                                  label: AppHelpers.trans(TrKeys.password)
                                      .toUpperCase(),
                                  obscure: state.showPassword,
                                  suffixIcon: IconButton(
                                    splashRadius: 25,
                                    icon: Icon(
                                      state.showPassword
                                          ? FlutterRemix.eye_line
                                          : FlutterRemix.eye_close_line,
                                      color: isDarkMode
                                          ? Style.blackColor
                                          : Style.hintColor,
                                      size: 20.r,
                                    ),
                                    onPressed: () => event.toggleShowPassword(),
                                  ),
                                  onChanged: (name) => event.setPassword(name),
                                  isError: state.isPasswordInvalid,
                                  descriptionText: state.isPasswordInvalid
                                      ? AppHelpers.trans(TrKeys
                                          .passwordShouldContainMinimum6Characters)
                                      : null,
                                ),
                                34.verticalSpace,
                                OutlinedBorderTextField(
                                  label:
                                      AppHelpers.trans(TrKeys.confirmPassword)
                                          .toUpperCase(),
                                  obscure: state.showConfirmPassword,
                                  suffixIcon: IconButton(
                                    splashRadius: 25,
                                    icon: Icon(
                                      state.showConfirmPassword
                                          ? FlutterRemix.eye_line
                                          : FlutterRemix.eye_close_line,
                                      color: isDarkMode
                                          ? Style.blackColor
                                          : Style.hintColor,
                                      size: 20.r,
                                    ),
                                    onPressed: () =>
                                        event.toggleShowConfirmPassword(),
                                  ),
                                  onChanged: (name) =>
                                      event.setConfirmPassword(name),
                                  isError: state.isConfirmPasswordInvalid,
                                  descriptionText: state
                                          .isConfirmPasswordInvalid
                                      ? AppHelpers.trans(
                                          TrKeys.confirmPasswordIsNotTheSame)
                                      : null,
                                ),
                              ],
                            ),
                    ],
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 30.h),
                    child: CustomButton(
                      isLoading: state.isLoading,
                      title: AppHelpers.trans(TrKeys.register),
                      onPressed: state.phone.isNotEmpty ? () {
                        isOnlyEmail
                            ? (event.checkEmail()
                                ? event.sendCode(context, () {
                                    Navigator.pop(context);
                                    AppHelpers
                                        .showCustomModalBottomSheetWithoutIosIcon(
                                      context: context,
                                      modal: RegisterConfirmationPage(
                                          verificationId: "",
                                          userModel: UserData(
                                              firstname: state.firstName,
                                              lastname: state.lastName,
                                              phone: state.phone,
                                              email: state.email,
                                              password: state.password,
                                              confirmPassword:
                                                  state.confirmPassword)),
                                      isDarkMode: isDarkMode,
                                    );
                                  })
                                : event.checkPhone(
                                    context: context,
                                    onSuccess: () {
                                      event.sendCodeToNumber(context, (s) {
                                        Navigator.pop(context);
                                        AppHelpers
                                            .showCustomModalBottomSheetWithoutIosIcon(
                                          context: context,
                                          modal: RegisterConfirmationPage(
                                              verificationId: s,
                                              userModel: UserData(
                                                  firstname: state.firstName,
                                                  lastname: state.lastName,
                                                  phone: state.phone,
                                                  email: state.email,
                                                  password: state.password,
                                                  confirmPassword:
                                                      state.confirmPassword)),
                                          isDarkMode: isDarkMode,
                                        );
                                      });
                                    },
                                  ))
                            : event.registerWithPhone(context ,  ref
                            .watch(profileProvider).userData?.phone ?? "");
                      } : null,
                    ),
                  ),
                  32.verticalSpace,
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
