// ignore_for_file: unused_result

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:sms_autofill/sms_autofill.dart';
import 'package:venderfoodyman/infrastructure/models/data/user_data.dart';
import 'package:venderfoodyman/presentation/component/components.dart';

import '../../../application/confirmation/register_confirmation_provider.dart';
import '../../../infrastructure/services/services.dart';
import '../../styles/style.dart';
import 'register_page.dart';
import 'reset/set_password_page.dart';

class RegisterConfirmationPage extends ConsumerStatefulWidget {
  final UserData userModel;
  final bool isResetPassword;
  final String verificationId;

  const RegisterConfirmationPage({
    Key? key,
    required this.userModel,
    this.isResetPassword = false,
    required this.verificationId,
  }) : super(key: key);

  @override
  ConsumerState<RegisterConfirmationPage> createState() =>
      _RegisterConfirmationPageState();
}

class _RegisterConfirmationPageState
    extends ConsumerState<RegisterConfirmationPage> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ref.refresh(registerConfirmationProvider);
      ref.read(registerConfirmationProvider.notifier).startTimer();
    });
  }

  @override
  void deactivate() {
    ref.read(registerConfirmationProvider.notifier).disposeTimer();
    super.deactivate();
  }

  @override
  Widget build(BuildContext context) {
    final notifier = ref.read(registerConfirmationProvider.notifier);
    final state = ref.watch(registerConfirmationProvider);
    final bool isDarkMode = LocalStorage.instance.getAppThemeMode();
    final bool isLtr = LocalStorage.instance.getLangLtr();
    ref.listen(registerConfirmationProvider, (previous, next) {
      if (previous!.isSuccess != next.isSuccess && next.isSuccess) {
        Navigator.pop(context);
        AppHelpers.showCustomModalBottomSheetWithoutIosIcon(
          context: context,
          modal: const RegisterPage(
            isOnlyEmail: false,
          ),
          isDarkMode: isDarkMode,
        );
      }
      if (previous.isResetPasswordSuccess != next.isResetPasswordSuccess &&
          next.isResetPasswordSuccess) {
        Navigator.pop(context);
        AppHelpers.showCustomModalBottomSheetWithoutIosIcon(
          context: context,
          modal: const SetPasswordPage(),
          isDarkMode: isDarkMode,
        );
      }
    });
    return Directionality(
      textDirection: isLtr ? TextDirection.ltr : TextDirection.rtl,
      child: AbsorbPointer(
        absorbing: state.isLoading || state.isResending,
        child: KeyboardDisable(
          child: Container(
            padding: 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: const EdgeInsets.all(16.0),
              child: SingleChildScrollView(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Column(
                      children: [
                        AppBarBottomSheet(
                          title: AppHelpers.trans(TrKeys.enterOtp),
                        ),
                        Text(
                          AppHelpers.trans(TrKeys.sendOtp),
                          style: Style.interRegular(
                            size: 14,
                            color: Style.blackColor,
                          ),
                        ),
                        Text(
                          widget.userModel.email ?? "",
                          style: Style.interRegular(
                            size: 14,
                            color: Style.blackColor,
                          ),
                        ),
                        40.verticalSpace,
                        SizedBox(
                          height: 64,
                          child: PinFieldAutoFill(
                            codeLength: 6,
                            currentCode: state.confirmCode,
                            onCodeChanged: notifier.setCode,
                            cursor: Cursor(
                              width: 1,
                              height: 24,
                              color: isDarkMode ? Style.white : Style.blackColor,
                              enabled: true,
                            ),
                            decoration: BoxLooseDecoration(
                              gapSpace: 10.r,
                              textStyle: Style.interNormal(
                                size: 15.sp,
                                color: isDarkMode ? Style.white : Style.blackColor,
                              ),
                              bgColorBuilder: FixedColorBuilder(
                                isDarkMode ? Style.blackColor : Style.transparent,
                              ),
                              strokeColorBuilder: FixedColorBuilder(
                                state.isCodeError
                                    ? Style.redColor
                                    : isDarkMode
                                    ? Style.borderColor
                                    : Style.blackColor,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Padding(
                      padding: EdgeInsets.only(
                          bottom: MediaQuery.of(context).padding.bottom,
                          top: 120.h),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          CustomButton(
                            isLoading: state.isResending,
                            title: state.isTimeExpired
                                ? AppHelpers.trans(TrKeys.resendOtp)
                                : state.timerText,
                            onPressed: () {
                              if (state.isTimeExpired) {
                                widget.verificationId.isEmpty
                                    ? notifier.resendConfirmation(
                                    context, widget.userModel.phone ?? "",
                                    isResetPassword: widget.isResetPassword)
                                    : notifier.sendCodeToNumber(
                                  context,
                                  widget.userModel.phone ?? "",
                                );
                                notifier.startTimer();
                              }
                            },
                            weight: (MediaQuery.sizeOf(context).width - 40) / 3,
                            background: Style.blackColor,
                            textColor: Style.white,
                          ),
                          CustomButton(
                            isLoading: state.isLoading,
                            title: AppHelpers.trans(TrKeys.confirmation),
                            onPressed: () {
                              if (state.confirmCode.length == 6) {
                                if (widget.isResetPassword) {
                                  widget.verificationId.isEmpty
                                      ? notifier.confirmCodeResetPassword(
                                      context, widget.userModel.phone ?? "")
                                      : notifier
                                      .confirmCodeResetPasswordWithPhone(
                                      context,
                                      widget.userModel.phone ?? "",
                                      widget.verificationId);
                                } else {
                                  widget.verificationId.isEmpty
                                      ? notifier.confirmCode(context)
                                      : notifier.confirmCodeWithFirebase(
                                      context: context,
                                      verificationId:
                                      widget.verificationId);
                                }
                              }
                            },
                            weight:
                            2 * (MediaQuery.sizeOf(context).width - 40) / 3,
                            background: state.isConfirm
                                ? Style.primaryColor
                                : Style.white,
                            textColor: Style.blackColor,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
