import 'package:farm_tpf/custom_model/password.dart';
import 'package:farm_tpf/data/api/app_exception.dart';
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 ChangePasswordScreen extends StatefulWidget {
  @override
  _ChangePasswordScreenState createState() => _ChangePasswordScreenState();
}

class _ChangePasswordScreenState extends State<ChangePasswordScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final _repository = UserRepository();
  GlobalKey<FormState> _formKey = GlobalKey();
  bool _autoValidate = false;

  Password _password = Password();
  TextEditingController _currentPasswordController = TextEditingController();
  TextEditingController _newPasswordController = TextEditingController();
  TextEditingController _confirmPasswordController = TextEditingController();

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

  _validateInputs() async {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      LoadingDialog.showLoadingDialog(context);
      _repository.changePassword(_password).then((value) {
        LoadingDialog.hideLoadingDialog(context);
        Navigator.pop(context);
        Utils.showSnackBarSuccess(message: "Cập nhật thành công");
      }).catchError((onError) {
        LoadingDialog.hideLoadingDialog(context);
        Utils.showSnackBarError(message: AppException.handleError(onError, customMessageError: "Sai mật khẩu hiện tại"));
      });
    } else {
      _autoValidate = true;
    }
  }

  Widget _currentPasswordField() {
    return TextFormField(
      keyboardType: TextInputType.text,
      obscureText: true,
      decoration: const InputDecoration(labelText: "Mật khẩu hiện tại"),
      controller: _currentPasswordController,
      validator: (String? value) {
        return Validators.validateNotNullOrEmpty(value ?? '', "Mật khẩu hiện tại");
      },
      onSaved: (newValue) {
        _password.currentPassword = newValue ?? '';
      },
    );
  }

  Widget _newPasswordField() {
    return TextFormField(
      keyboardType: TextInputType.text,
      obscureText: true,
      decoration: const InputDecoration(labelText: "Mật khẩu mới"),
      controller: _newPasswordController,
      validator: (v) {
        return validators.validateNewPassword(v ?? '');
      },
      onSaved: (newValue) {
        _password.newPassword = newValue ?? '';
      },
    );
  }

  Widget _confirmPasswordField() {
    return TextFormField(
      keyboardType: TextInputType.text,
      obscureText: true,
      decoration: const InputDecoration(labelText: "Nhập lại mật khẩu mới"),
      controller: _confirmPasswordController,
      validator: (String? value) {
        return validators.validateConfirmPassword(_newPasswordController.text, value ?? '');
      },
      onSaved: (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(
          'Cập nhật'.toUpperCase(),
          style: TextStyle(fontWeight: FontWeight.bold, color: AppColors.WHITE),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) => KeyboardDismisser(
      child: Scaffold(
          backgroundColor: Colors.white,
          key: _scaffoldKey,
          appBar: AppBarWidget(
            isBack: true,
          ),
          body: KeyboardDismisser(
              child: Form(
                  key: _formKey,
                  // autovalidate: _autoValidate,
                  child: SingleChildScrollView(
                    padding: const EdgeInsets.all(8.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        const Text(
                          'Bảo mật',
                          style: TextStyle(fontWeight: FontWeight.w500, fontSize: 22),
                        ),
                        const Text('Cập nhật mật khẩu cho tài khoản của bạn. Mật khẩu bao gồm cả chữ và số, độ dài tối thiểu 8 ký tự',
                            style: TextStyle(fontSize: 15, fontWeight: FontWeight.w200, color: Colors.black54)),
                        _currentPasswordField(),
                        const SizedBox(
                          height: 8.0,
                        ),
                        _newPasswordField(),
                        const SizedBox(
                          height: 8.0,
                        ),
                        _confirmPasswordField(),
                        const SizedBox(
                          height: 20.0,
                        ),
                        _btnSubmit()
                      ],
                    ),
                  )))));
}
