import 'package:didvan/providers/user_provider.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/views/authentication/authentication_state.dart';
import 'package:didvan/views/authentication/widgets/authentication_layout.dart';
import 'package:didvan/views/widgets/didvan/button.dart';
import 'package:didvan/views/widgets/didvan/text_field.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ResetPassword extends StatefulWidget {
  const ResetPassword({Key? key}) : super(key: key);

  @override
  State<ResetPassword> createState() => _ResetPasswordState();
}

class _ResetPasswordState extends State<ResetPassword> {
  String _password = '';
  String _passwordConfirmation = '';
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: AuthenticationLayout(
        children: [
          DidvanTextField(
            title: 'کلمه عبور جدید',
            onChanged: (value) => _password = value,
            validator: (value) => value.length < 8
                ? 'کلمه عبور نمی‌تواند کمتر از 8 کاراکتر داشته باشد'
                : null,
            hintText: 'کلمه عبور جدید',
            obsecureText: true,
          ),
          const SizedBox(
            height: 16,
          ),
          DidvanTextField(
            title: 'تکرار کلمه عبور جدید',
            onChanged: (value) => _passwordConfirmation = value,
            validator: (value) => _passwordConfirmation != _password
                ? 'تکرار کلمه عبور با کلمه عبور یکسان نیست'
                : null,
            hintText: 'تکرار کلمه عبور جدید',
            obsecureText: true,
          ),
          const Spacer(),
          DidvanButton(
            onPressed: () async {
              if (!_formKey.currentState!.validate()) return;
              final result = await context
                  .read<AuthenticationState>()
                  .resetPassword(_password);
              if (result && context.read<UserProvider>().isAuthenticated) {
                Navigator.of(context).pop();
                Navigator.of(context).pop();
                return;
              }
              Navigator.of(context).pushNamed(
                Routes.authenticaion,
                arguments: false,
              );
            },
            title: 'تغییر رمز عبور',
          ),
          const SizedBox(
            height: 48,
          ),
        ],
      ),
    );
  }
}
