import 'package:didvan/providers/server_data.dart';
import 'package:didvan/providers/user.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) {
    final authState = context.watch<AuthenticationState>();
    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 authState = context.read<AuthenticationState>();
              final userProvider = context.read<UserProvider>();

              final bool resetSuccess =
                  await authState.resetPassword(_password);

              if (resetSuccess && mounted) {
                authState.password = _password;
                final String? token = await authState.login(userProvider);

                if (token != null && mounted) {
                  await ServerDataProvider.getData();
                  Navigator.of(context).pushNamedAndRemoveUntil(
                    Routes.home,
                    (_) => false,
                    arguments: true,
                  );
                }
              }
            },
            title: authState.hasPassword ? 'تغییر رمز عبور' : 'تایید رمز عبور',
          ),
          const SizedBox(
            height: 48,
          ),
        ],
      ),
    );
  }
}
