import 'package:easy_debounce/easy_debounce.dart';
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hub/features/auth/index.dart';
import 'package:hub/features/storage/index.dart';
import 'package:hub/flutter_flow/nav/nav.dart';

import '../../flutter_flow/flutter_flow_animations.dart';
import '../../flutter_flow/flutter_flow_icon_button.dart';
import '../../flutter_flow/flutter_flow_model.dart';
import '../../flutter_flow/flutter_flow_theme.dart';
import '../../flutter_flow/flutter_flow_widgets.dart';
import '../../flutter_flow/internationalization.dart';
import 'forgot_password_model.dart';

class ForgotPasswordScreen extends StatefulWidget {
  const ForgotPasswordScreen(
      {super.key, required this.email, required this.token});
  final String email;
  final String token;

  @override
  State<ForgotPasswordScreen> createState() => _ForgotPasswordScreenState();
}

class _ForgotPasswordScreenState extends State<ForgotPasswordScreen>
    with TickerProviderStateMixin {
  late ForgotPasswordScreenModel _model;
  final animationsMap = <String, AnimationInfo>{};

  @override
  void setState(VoidCallback callback) {
    super.setState(callback);
    _model.onUpdate();
  }

  @override
  void initState() {
    super.initState();
    _model = createModel(context, () => ForgotPasswordScreenModel());

    _model.passwordRegisterFormTextController ??= TextEditingController();
    _model.passwordRegisterFormFocusNode ??= FocusNode();
    _model.passwordRegisterFormFocusNode!.addListener(() => setState(() {}));

    _model.passwordConfirmFormTextController ??= TextEditingController();
    _model.passwordConfirmFormFocusNode ??= FocusNode();
    _model.passwordConfirmFormFocusNode!.addListener(() => setState(() {}));

    animationsMap.addAll({
      'containerOnPageLoadAnimation': AnimationInfo(
        trigger: AnimationTrigger.onPageLoad,
        effectsBuilder: () => [
          VisibilityEffect(duration: 1.ms),
          FadeEffect(
            curve: Curves.easeInOut,
            delay: 0.0.ms,
            duration: 300.0.ms,
            begin: 0.0,
            end: 1.0,
          ),
          MoveEffect(
            curve: Curves.easeInOut,
            delay: 0.0.ms,
            duration: 300.0.ms,
            begin: const Offset(0.0, 140.0),
            end: const Offset(0.0, 0.0),
          ),
          ScaleEffect(
            curve: Curves.easeInOut,
            delay: 0.0.ms,
            duration: 300.0.ms,
            begin: const Offset(0.9, 0.9),
            end: const Offset(1.0, 1.0),
          ),
          TiltEffect(
            curve: Curves.easeInOut,
            delay: 0.0.ms,
            duration: 300.0.ms,
            begin: const Offset(-0.349, 0),
            end: const Offset(0, 0),
          ),
        ],
      ),
    });
  }

  @override
  void dispose() {
    _model.maybeDispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) => buildBody(context);

  AppBar buildAppBar(BuildContext context) {
    return AppBar(
      automaticallyImplyLeading: false,
      forceMaterialTransparency: true,
      leading: FlutterFlowIconButton(
        borderColor: Colors.transparent,
        borderRadius: 30.0,
        borderWidth: 1.0,
        buttonSize: 60.0,
        icon: Icon(
          Icons.keyboard_arrow_left,
          color: FlutterFlowTheme.of(context).primaryText,
          size: 30.0,
        ),
        onPressed: () async {
          context.pop();
          StorageHelper().isRecovered = false;
        },
      ),
      title: Text(
        key: ValueKey('ForgotPasswordText'),
        FFLocalizations.of(context).getVariableText(
          ptText: 'Recuperar Senha',
          enText: 'Recover Password',
        ),
        style: FlutterFlowTheme.of(context).headlineMedium.override(
              fontFamily: 'Nunito',
              color: FlutterFlowTheme.of(context).primaryText,
              fontSize: 15.0,
              fontWeight: FontWeight.bold,
              letterSpacing: 0.0,
              useGoogleFonts: GoogleFonts.asMap().containsKey('Nunito'),
            ),
      ),
      actions: const [],
      centerTitle: true,
      elevation: 0.0,
    );
  }

  Widget buildBody(BuildContext context) {
    late final String title = FFLocalizations.of(context).getVariableText(
      ptText: 'Recuperar Senha',
      enText: 'Recover Password',
    );
    late final String message = FFLocalizations.of(context).getVariableText(
      ptText: 'Qual será a sua nova senha? Insira abaixo e confirme.',
      enText: 'What will be your new password? Enter it below and confirm.',
    );
    return SizedBox(
      height: 400,
      width: MediaQuery.of(context).size.width,
      child: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.only(
              left: 15.0, right: 15.0, top: 10.0, bottom: 0.0),
          child: Container(
            width: double.infinity,
            constraints: const BoxConstraints(maxWidth: 570.0),
            decoration: BoxDecoration(
              color: FlutterFlowTheme.of(context).primaryBackground,
              borderRadius: BorderRadius.circular(12.0),
            ),
            child: Padding(
              padding: const EdgeInsets.only(
                  left: 20.0, right: 20.0, top: 10.0, bottom: 0.0),
              child: Column(
                mainAxisSize: MainAxisSize.max,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Center(
                      child: Text(
                    title,
                    style: FlutterFlowTheme.of(context).title1.override(
                          fontFamily: 'Nunito',
                          color: FlutterFlowTheme.of(context).primaryText,
                          fontSize: 24.0,
                          fontWeight: FontWeight.bold,
                          letterSpacing: 0.0,
                          useGoogleFonts:
                              GoogleFonts.asMap().containsKey('Nunito'),
                        ),
                  )),
                  Align(
                    alignment: const AlignmentDirectional(-1.0, 0.0),
                    child: Padding(
                      padding: const EdgeInsetsDirectional.fromSTEB(
                          20.0, 24.0, 0.0, 30.0),
                      child: Text(
                        message,
                        textAlign: TextAlign.start,
                        style: FlutterFlowTheme.of(context).bodyMedium.override(
                              fontFamily:
                                  FlutterFlowTheme.of(context).bodyMediumFamily,
                              fontWeight: FontWeight.bold,
                              useGoogleFonts: GoogleFonts.asMap().containsKey(
                                  FlutterFlowTheme.of(context)
                                      .bodyMediumFamily),
                            ),
                      ),
                    ),
                  ),
                  Form(
                    key: _model.formKey,
                    autovalidateMode: AutovalidateMode.onUserInteraction,
                    child: Column(
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        _buildPasswordField(
                          context,
                          controller: _model.passwordRegisterFormTextController,
                          focusNode: _model.passwordRegisterFormFocusNode,
                          visibility: _model.passwordRegisterFormVisibility,
                          onVisibilityToggle: () => setState(() =>
                              _model.passwordRegisterFormVisibility =
                                  !_model.passwordRegisterFormVisibility),
                          label: FFLocalizations.of(context).getVariableText(
                              ptText: 'Nova Senha', enText: 'New Password'),
                          hint: FFLocalizations.of(context).getVariableText(
                              ptText: 'Insira sua senha',
                              enText: 'Enter your password'),
                          asValidator: _model
                              .passwordRegisterFormTextControllerValidator
                              .asValidator(context),
                        ),
                        _buildPasswordField(
                          context,
                          controller: _model.passwordConfirmFormTextController,
                          focusNode: _model.passwordConfirmFormFocusNode,
                          visibility: _model.passwordConfirmFormVisibility,
                          onVisibilityToggle: () => setState(() =>
                              _model.passwordConfirmFormVisibility =
                                  !_model.passwordConfirmFormVisibility),
                          label: FFLocalizations.of(context).getVariableText(
                              ptText: 'Confirme a Senha',
                              enText: 'Confirm Password'),
                          hint: FFLocalizations.of(context).getVariableText(
                              ptText: 'Confirme sua senha',
                              enText: 'Confirm your password'),
                          asValidator: _model
                              .passwordConfirmFormTextControllerValidator
                              .asValidator(context),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsetsDirectional.fromSTEB(
                        0.0, 0.0, 0.0, 16.0),
                    child: FFButtonWidget(
                      key: const ValueKey<String>('SubmitButtonWidget'),
                      onPressed: _model.isFormInvalid()
                          ? null
                          : () async {
                              await AuthenticationService.changePassword(
                                context,
                                widget.email,
                                _model.passwordConfirmFormTextController!.text,
                                widget.token,
                              ).then((v) => v == true ? context.pop() : null);
                              setState(() {});
                            },
                      text: FFLocalizations.of(context).getVariableText(
                        ptText: 'Enviar',
                        enText: 'Submit',
                      ),
                      options: FFButtonOptions(
                        width: double.infinity,
                        height: 44.0,
                        color: FlutterFlowTheme.of(context).accent1,
                        textStyle: FlutterFlowTheme.of(context)
                            .titleSmall
                            .override(
                                fontFamily: 'Plus Jakarta Sans',
                                color:
                                    FlutterFlowTheme.of(context).secondaryText,
                                fontSize: 16.0,
                                fontWeight: FontWeight.w500,
                                useGoogleFonts: GoogleFonts.asMap()
                                    .containsKey('Plus Jakarta Sans')),
                        elevation: 3.0,
                        borderSide: const BorderSide(
                            color: Colors.transparent, width: 1.0),
                        borderRadius: BorderRadius.circular(12.0),
                        disabledColor:
                            FlutterFlowTheme.of(context).customColor5,
                        disabledTextColor: Colors.white,
                      ),
                      showLoadingIndicator: true,
                    ),
                  ),
                ],
              ),
            ),
          ).animateOnPageLoad(animationsMap['containerOnPageLoadAnimation']!),
        ),
      ),
    );
  }

  Widget _buildPasswordField(BuildContext context,
      {required TextEditingController? controller,
      required FocusNode? focusNode,
      required bool visibility,
      required VoidCallback onVisibilityToggle,
      required String hint,
      required String label,
      required String? Function(String?)? asValidator}) {
    return Padding(
      padding: const EdgeInsetsDirectional.fromSTEB(0.0, 0.0, 0.0, 16.0),
      child: SizedBox(
        width: double.infinity,
        child: TextFormField(
          key: const ValueKey<String>('passwordTextFormField'),
          controller: controller,
          focusNode: focusNode,
          onChanged: (_) => EasyDebounce.debounce(
            '_model.passwordRegisterFormTextController',
            const Duration(milliseconds: 500),
            () => setState(() {}),
          ),
          autofocus: false,
          autofillHints: const [AutofillHints.password],
          obscureText: !visibility,
          decoration: InputDecoration(
            isDense: true,
            hintText: hint,
            labelText: label,
            labelStyle: FlutterFlowTheme.of(context).labelLarge.override(
                  fontFamily: 'Plus Jakarta Sans',
                  color: FlutterFlowTheme.of(context).primaryText,
                  fontSize: 16.0,
                  fontWeight: FontWeight.w500,
                  useGoogleFonts:
                      GoogleFonts.asMap().containsKey('Plus Jakarta Sans'),
                ),
            enabledBorder: OutlineInputBorder(
              borderSide: BorderSide(
                  color: FlutterFlowTheme.of(context).customColor1,
                  width: 0.25),
              borderRadius: BorderRadius.circular(12.0),
            ),
            focusedBorder: OutlineInputBorder(
              borderSide:
                  const BorderSide(color: Color(0xFF1AAB5F), width: 0.25),
              borderRadius: BorderRadius.circular(12.0),
            ),
            errorBorder: OutlineInputBorder(
              borderSide:
                  const BorderSide(color: Color(0xFFFF5963), width: 0.25),
              borderRadius: BorderRadius.circular(12.0),
            ),
            focusedErrorBorder: OutlineInputBorder(
              borderSide:
                  const BorderSide(color: Color(0xFFFF5963), width: 0.25),
              borderRadius: BorderRadius.circular(12.0),
            ),
            filled: true,
            fillColor: FlutterFlowTheme.of(context).primaryBackground,
            suffixIcon: InkWell(
              key: const ValueKey<String>('passwordVisibilitySuffixIcon'),
              onTap: onVisibilityToggle,
              focusNode: FocusNode(skipTraversal: true),
              child: Icon(
                visibility
                    ? Icons.visibility_outlined
                    : Icons.visibility_off_outlined,
                color: FlutterFlowTheme.of(context).accent1,
                size: 24.0,
              ),
            ),
          ),
          style: FlutterFlowTheme.of(context).bodyLarge.override(
                fontFamily: 'Plus Jakarta Sans',
                color: FlutterFlowTheme.of(context).primaryText,
                fontSize: 16.0,
                fontWeight: FontWeight.w500,
                useGoogleFonts:
                    GoogleFonts.asMap().containsKey('Plus Jakarta Sans'),
              ),
          validator: asValidator,
        ),
      ),
    );
  }
}
