import 'package:farm_tpf/data/repository/user_repository.dart';
import 'package:farm_tpf/presentation/custom_widgets/app_bar_widget.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_loading.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_utils.dart';
import 'package:farm_tpf/utils/const_color.dart';
import 'package:farm_tpf/utils/validators.dart';
import 'package:flutter/material.dart';
import 'package:keyboard_dismisser/keyboard_dismisser.dart';

class ForgotPasswordScreen extends StatefulWidget {
  @override
  _ForgotPasswordScreenState createState() => _ForgotPasswordScreenState();
}

class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> {
  UserRepository _userRepository = UserRepository();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  GlobalKey<FormState> _formKey = GlobalKey();
  bool _autoValidate = false;
  TextEditingController _emailController = TextEditingController();
  String _email = "";

  @override
  void initState() {
    super.initState();
  }

  _validateInputs() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      LoadingDialog.showLoadingDialog(context);
      _userRepository.forgotPassword(_email).then((value) {
        LoadingDialog.hideLoadingDialog(context);
        Navigator.pop(context);
        Utils.showSnackBarSuccess(message: "Gửi email thành công");
      }).catchError((error) {
        LoadingDialog.hideLoadingDialog(context);
        Utils.showSnackBarError(message: 'Email không tồn tại');
      });
    } else {
      _autoValidate = true;
    }
  }

  Widget _emailField() {
    return TextFormField(
      keyboardType: TextInputType.text,
      decoration: const InputDecoration(labelText: "Email"),
      controller: _emailController,
      validator: (String? value) {
        return Validators.validateEmail(value ?? '');
      },
      onSaved: (newValue) {
        _email = newValue ?? '';
      },
    );
  }

  Widget _btnSubmit() {
    return SizedBox(
      width: double.infinity,
      height: 55,
      child: FlatButton(
        onPressed: () {
          var currentFocus = FocusScope.of(context);
          if (!currentFocus.hasPrimaryFocus) {
            currentFocus.unfocus();
          }
          _validateInputs();
        },
        color: AppColors.DEFAULT,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(7.0),
        ),
        child: Text(
          'Gửi'.toUpperCase(),
          style: TextStyle(fontWeight: FontWeight.bold, color: AppColors.WHITE),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) => KeyboardDismisser(
      child: Scaffold(
          backgroundColor: Colors.white,
          key: _scaffoldKey,
          appBar: AppBarWidget(),
          body: Form(
              key: _formKey,
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    const SizedBox(
                      height: 14,
                    ),
                    const Text(
                      'Quên mật khẩu',
                      style: TextStyle(fontSize: 26, fontWeight: FontWeight.w300, color: Colors.black),
                    ),
                    const SizedBox(
                      height: 8,
                    ),
                    const Text('Nhập email đăng ký mật khẩu vào ô bên dưới. Hệ thống sẽ gửi bạn một liên kết đặt lại mật khẩu qua email.',
                        style: TextStyle(fontSize: 15, fontWeight: FontWeight.w200, color: Colors.black54)),
                    _emailField(),
                    const SizedBox(
                      height: 16.0,
                    ),
                    _btnSubmit()
                  ],
                ),
              ))));
}
