
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 DesktopSetPassword extends StatefulWidget {
  final String mobile;
  final String code;

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

  @override
  State<StatefulWidget> createState() =>
    DesktopSetPasswordState();
}

class DesktopSetPasswordState extends State<DesktopSetPassword> {
  final GlobalKey<FormState> _formKey = GlobalKey();

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

  bool passwordVisible;
  bool passwordAgainVisible;

  bool canReset;

  double sideSpace = 0;
  double mainSpace = 1200;

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

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

    if (MediaQuery.of(context).size.width <= 1200) {
      mainSpace = MediaQuery.of(context).size.width;
      sideSpace = 0;
    } else {
      mainSpace = 1200;
      sideSpace = (MediaQuery.of(context).size.width - 1200) / 2;
    }

    Widget form = 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,
                ),
              ),
            ),
          ],
        ),
      ),
    );

    return SingleChildScrollView(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: sideSpace,
          ),
          Container(
            width: mainSpace,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: mainSpace / 2,
                  margin: EdgeInsets.only(top: 16.0, bottom: 16.0),
                  padding: EdgeInsets.all(10.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        padding: EdgeInsets.only(left: 16.0, top: 0.0, right: 16.0),
                        child: Text(
                          S.of(context).set_password,
                          style: TextStyle(
                              fontSize: 24.0,
                              color: Colors.black
                          ),
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.only(top: 12.0, left: 16.0, right: 16.0, bottom: 12.0),
                        child: Text(
                          S.of(context).set_password_desc,
                          style: TextStyle(
                            color: Colors.black54,
                            fontSize: 14.0,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: mainSpace / 2,
                  margin: EdgeInsets.only(top: 16.0, bottom: 16.0),
                  padding: EdgeInsets.all(10.0),
                  decoration: BoxDecoration(
                    border: Border(
                      left: BorderSide(
                        width: 1.0,
                        color: Colors.black12,
                      ),
                    ),
                  ),
                  child: form,
                ),
              ],
            ),
          ),
          Container(
            width: sideSpace,
          ),
        ],
      ),
    );
  }


  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).reset_password_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);
      });
    }
  }
}