import 'dart:io';

//import 'package:firebase_auth/firebase_auth.dart' as auth;
//import 'package:flutter/cupertino.dart';
import 'package:adaptive_action_sheet/adaptive_action_sheet.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jubo/control/authService.dart';
import 'package:jubo/control/personService.dart';
import 'package:jubo/main.dart';
import 'package:jubo/model/person.dart';
import 'package:jubo/preLogin.dart';
import 'package:jubo/ui/loading.dart';
import 'package:jubo/ui/settings.dart';
import 'package:jubo/ui/sucess.dart';
import '../util/params.dart';
//import 'package:flutter_login_screen/main.dart';
//import 'package:flutter_login_screen/model/user.dart';
//import 'package:flutter_login_screen/services/authenticate.dart';
import '../util/helper.dart';
//import 'package:flutter_login_screen/ui/home/homeScreen.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
import 'package:image/image.dart' as ImageProcess;

File _image;

class ChangePassword extends StatefulWidget {
  ChangePassword({this.fName});
  final String fName;
  @override
  State createState() => _ChangePasswordState();
}

class _ChangePasswordState extends State<ChangePassword> {
  final ImagePicker _imagePicker = ImagePicker();
  TextEditingController _passwordController = new TextEditingController();
  GlobalKey<FormState> _key = new GlobalKey();
  AutovalidateMode _validate = AutovalidateMode.disabled;
  String currentPassword, newPassword, confirmNewPassword;
  bool loading=false;
  bool sucess=false;
  int id;

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

  void loadPerson() async {
    setState(() => loading = true);
    AuthenticationService auth = new AuthenticationService();
    await Future.delayed(Duration(seconds: 1));
    ModelPerson loggedPerson = await auth.getPerson();
    setState(() {
      id = loggedPerson.id;
      loading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    /**if (Platform.isAndroid) {
      retrieveLostData();
    }
**/

    return loading
        ? Loading()
        : sucess
        ? Sucess()
        : Scaffold(
      appBar: AppBar(
        elevation: 5.0,
        backgroundColor: COLOR_PRIMARY,
        title: Text("Alterar Minha Senha"),
        leading: TextButton(
          child: Icon(
            Icons.arrow_back,
            size: 30.0,
            color: Colors.white,
          ),
          onPressed: () {
            Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                    builder: (context) => MyStatefulWidget(
                          selectedIndex: 3,
                        )));
          },
        ),
      ),
      body: SingleChildScrollView(
        child: new Container(
          margin: new EdgeInsets.only(left: 16.0, right: 16, bottom: 16),
          child: new Form(
            key: _key,
            autovalidateMode: _validate,
            child: formUI(),
          ),
        ),
      ),
    );
  }

  Widget formUI() {
    return new Column(
      children: <Widget>[
        SizedBox(height: 10,),
        ConstrainedBox(
            constraints: BoxConstraints(minWidth: double.infinity),
            child: Padding(
              padding: const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
              child: TextFormField(
                  obscureText: true,
                  textInputAction: TextInputAction.next,
                  onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                  onSaved: (String val) {
                    currentPassword = val;
                  },
                  style: TextStyle(height: 0.8, fontSize: 18.0),
                  cursorColor: COLOR_PRIMARY,
                  decoration: InputDecoration(
                      contentPadding:
                          new EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                      fillColor: Colors.white,
                      hintText: 'Senha Atual',
                      focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                          borderSide:
                              BorderSide(color: COLOR_PRIMARY, width: 2.0)),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10.0),
                      ))),
            )),
        ConstrainedBox(
            constraints: BoxConstraints(minWidth: double.infinity),
            child: Padding(
              padding: const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
              child: TextFormField(
                  obscureText: true,
                  textInputAction: TextInputAction.next,
                  onFieldSubmitted: (_) => FocusScope.of(context).nextFocus(),
                  controller: _passwordController,
                  validator: validatePassword,
                  onSaved: (String val) {
                    newPassword = val;
                  },
                  style: TextStyle(height: 0.8, fontSize: 18.0),
                  cursorColor: COLOR_PRIMARY,
                  decoration: InputDecoration(
                      contentPadding:
                          new EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                      fillColor: Colors.white,
                      hintText: 'Senha',
                      focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10.0),
                          borderSide:
                              BorderSide(color: COLOR_PRIMARY, width: 2.0)),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10.0),
                      ))),
            )),
        ConstrainedBox(
          constraints: BoxConstraints(minWidth: double.infinity),
          child: Padding(
            padding: const EdgeInsets.only(top: 16.0, right: 8.0, left: 8.0),
            child: TextFormField(
                textInputAction: TextInputAction.done,
                onFieldSubmitted: (_) {
                  //_sendToServer();
                },
                obscureText: true,
                validator: (val) =>
                    validateConfirmPassword(_passwordController.text, val),
                onSaved: (String val) {
                  confirmNewPassword = val;
                },
                style: TextStyle(height: 0.8, fontSize: 18.0),
                cursorColor: COLOR_PRIMARY,
                decoration: InputDecoration(
                    contentPadding:
                        new EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                    fillColor: Colors.white,
                    hintText: 'Confirmar senha',
                    focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(10.0),
                        borderSide:
                            BorderSide(color: COLOR_PRIMARY, width: 2.0)),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10.0),
                    ))),
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(right: 8.0, left: 8.0, top: 40.0),
          child: ConstrainedBox(
            constraints: const BoxConstraints(minWidth: double.infinity),
            child: ElevatedButton(
              onPressed: _sendToServer,
              style: ElevatedButton.styleFrom(
                primary: COLOR_PRIMARY,
                padding: EdgeInsets.only(top: 15, bottom: 15),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25.0),
                    side: BorderSide(color: COLOR_PRIMARY)),
              ),
              child: Text(
                'Salvar',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(right: 8.0, left: 8.0, top: 10.0),
          child: ConstrainedBox(
            constraints: const BoxConstraints(minWidth: double.infinity),
            child: ElevatedButton(
              onPressed: () {
                Navigator.pop(context);
              },
              style: ElevatedButton.styleFrom(
                primary: Color(0xFF822A41),
                padding: EdgeInsets.only(top: 15, bottom: 15),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(25.0),
                    side: BorderSide(color: Color(0xFF822A41))),
              ),
              child: Text(
                'Cancelar',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  _sendToServer() async {
    if (_key.currentState.validate()) {
      setState(() {
        loading = true;
        sucess = false;
      });
      _key.currentState.save();

      await new Future.delayed(const Duration(seconds: 1));

      var m = null;

      PersonService service = new PersonService();

      try {
        await service.changePassword(id, currentPassword, confirmNewPassword);
        setState(() {
          loading = false;
          sucess = true;
        });
        await new Future.delayed(const Duration(milliseconds: 1600));
        setState(() {
          loading = false;
          sucess = false;
        });
        //showAlertDialog(context, 'JuBo', "Cadastro Efetuado!");
        Navigator.pop(context);
      } catch (Exception) {
        setState(() => loading = false);
        //hideProgress();
        showAlertDialog(context, 'JuBo', "Problemas ao alterar senha!");
      }
    } else {
      setState(() {
        _validate = AutovalidateMode.onUserInteraction;
      });
    }
  }

  @override
  void dispose() {
    _passwordController.dispose();
    _image = null;
    super.dispose();
  }
}
