
import 'package:flutter/material.dart';

import '../../generated/l10n.dart';
import '../../routes.dart';
import '../../store/actions.dart';
import '../../store/store.dart';
import '../../utils/http_util.dart';
import '../../utils/utils.dart';

class MobileSetPassword extends StatefulWidget {
  final String mobile;
  final String code;

  const MobileSetPassword(this.mobile, {Key key, this.code}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return MobileSetPasswordState();
  }

}

class MobileSetPasswordState extends State<MobileSetPassword> {

  final GlobalKey<FormState> _formKey = GlobalKey();

  final passwordController = TextEditingController();
  final passwordAgainController = TextEditingController();

  bool passwordVisible;
  bool passwordAgainVisible;

  bool canReset;

  @override
  void initState() {
    super.initState();
    canReset = false;
    passwordVisible = true;
    passwordAgainVisible = true;
  }

  @override
  Widget build(BuildContext context) {
    store.dispatch(UpdateContext(context));

    return ListView(
      children: <Widget>[
        Container(
          padding: EdgeInsets.only(top: 16.0, left: 16.0, right: 16.0, bottom: 16.0),
          child: Text(
            S.of(context).set_password,
            style: TextStyle(
                fontSize: 24.0,
                color: Colors.black,
            ),
          ),
        ),
        Container(
          padding: EdgeInsets.only(top: 0.0, left: 16.0, right: 16.0, bottom: 16.0),
          child: Text(
            S.of(context).set_password_desc,
            style: TextStyle(
                fontSize: 14.0,
                color: Colors.black54,
            ),
          ),
        ),
        Container(
          padding: EdgeInsets.only(top: 0.0, left: 16.0, right: 16.0, bottom: 0.0),
          child: Form(
            key: _formKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  child: TextFormField(
                    controller: passwordController,
                    decoration: new InputDecoration(
                      enabledBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.black12,
                        ),
                      ),
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.blue,
                        ),
                      ),
                      labelText: S.of(context).password,
                      suffixIcon: IconButton(
                        icon: Icon(
                          passwordVisible ? Icons.visibility_off : Icons.visibility,
                          color: Theme.of(context).primaryColorDark,
                        ),
                        onPressed: () {
                          setState(() {
                            passwordVisible = !passwordVisible;
                          });
                        },
                      ),
                    ),
                    style: TextStyle(
                        fontSize: 18.0
                    ),
                    validator: (String value) {
                      if (value.trim().isEmpty) {
                        return S.of(context).password_is_required;
                      }
                      return null;
                    },
                    obscureText: passwordVisible,
                    onChanged: (string) {
                      if (string.trim().isNotEmpty && passwordAgainController.text.trim().isNotEmpty) {
                        if (mounted) {
                          setState(() {
                            canReset = true;
                          });
                        }
                      } else {
                        if (mounted) {
                          setState(() {
                            canReset = false;
                          });
                        }
                      }
                    },
                  ),
                ),
                Container(
                  child: TextFormField(
                    controller: passwordAgainController,
                    decoration: new InputDecoration(
                      enabledBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.black12,
                        ),
                      ),
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(
                          color: Colors.blue,
                        ),
                      ),
                      labelText: S.of(context).password_again,
                      suffixIcon: IconButton(
                        icon: Icon(
                          passwordAgainVisible ? Icons.visibility_off : Icons.visibility,
                          color: Theme.of(context).primaryColorDark,
                        ),
                        onPressed: () {
                          setState(() {
                            passwordAgainVisible = !passwordAgainVisible;
                          });
                        },
                      ),
                    ),
                    style: TextStyle(
                        fontSize: 18.0
                    ),
                    validator: (String value) {
                      if (value.trim().isEmpty) {
                        return S.of(context).password_is_required;
                      }
                      if (value.trim() != passwordController.text.trim()) {
                        return S.of(context).password_is_not_match_password_again;
                      }
                      return null;
                    },
                    obscureText: passwordAgainVisible,
                    onChanged: (string) {
                      if (passwordController.text.trim().isNotEmpty && string.trim().isNotEmpty) {
                        if (mounted) {
                          setState(() {
                            canReset = true;
                          });
                        }
                      } else {
                        if (mounted) {
                          setState(() {
                            canReset = false;
                          });
                        }
                      }
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
        Container(
          padding: EdgeInsets.only(right: 16.0, top: 16.0),
          child: Align(
            alignment: Alignment.centerRight,
            child: RaisedButton(
              color: Theme.of(context).primaryColor,
              child: Text(
                S.of(context).submit,
                style: TextStyle(
                  color: Colors.white,
                ),
              ),
              onPressed: canReset ? resetPassword : null,
            ),
          ),
        ),
      ],
    );
  }

  void resetPassword() {
    final FormState form = _formKey.currentState;
    if (form.validate()) {
      HttpUtil.httpPost('v1/users', (response) {
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text(S.of(context).success),
              content: Text(S.of(context).user_account_created_success),
              actions: <Widget>[
                FlatButton(
                  child: Text(S.of(context).ok),
                  onPressed: () {
                    Routes.router.navigateTo(context, '/login', replace: true, clearStack: false);
                  },
                ),
              ],
            );
          },
        );
      },
          queryParameters: {
            'action': 'create_user',
          },
          isFormData: true,
          body: {
            'mobile': widget.mobile,
            'code': widget.code,
            'password': passwordController.text.trim()
          }
      ).catchError((error) {
        Utils.showMessageDialog(context, error);
      });
    }
  }
}