import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:jubo/ui/loading.dart';
import 'package:jubo/control/authService.dart';
import 'package:jubo/util/helper.dart';
import 'util/params.dart';
import 'package:http/http.dart' as http;
import 'model/person.dart';
import 'main.dart';

class Login extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<Login> {
  bool _rememberMe = false;
  bool loading = false;

  UserLogin userLogin = new UserLogin();

  Widget _tfEmail() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        /*
        Text(
          'Email',
          style: kLabelStyle,
        ),
        SizedBox(height: 10.0),
        */
        Container(
          alignment: Alignment.centerLeft,
          decoration: kBoxDecorationStyle,
          height: 50.0,
          child: TextField(
            keyboardType: TextInputType.emailAddress,
            onChanged: (text) => userLogin.login = text,
            style: TextStyle(
              color: Color.fromRGBO(68, 49, 122, 1.0),
              fontFamily: 'OpenSans',
            ),
            decoration: InputDecoration(
              border: InputBorder.none,
              contentPadding: EdgeInsets.only(top: 14.0),
              prefixIcon: Icon(
                Icons.email,
                color: Color.fromRGBO(68, 49, 122, 1.0),
              ),
              hintText: 'Email',
              hintStyle: kHintTextStyle,
            ),
          ),
        ),
      ],
    );
  }

  Widget _tfPassword() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        /*
        Text(
          'Senha',
          style: kLabelStyle,
        ),
        SizedBox(height: 10.0),
        */
        Container(
          alignment: Alignment.centerLeft,
          decoration: kBoxDecorationStyle,
          height: 50.0,
          child: TextField(
            onChanged: (text) => userLogin.pass = text,
            obscureText: true,
            style: TextStyle(
              color: Color.fromRGBO(68, 49, 122, 1.0),
              fontFamily: 'OpenSans',
            ),
            decoration: InputDecoration(
              border: InputBorder.none,
              contentPadding: EdgeInsets.only(top: 14.0),
              prefixIcon: Icon(
                Icons.lock,
                color: Color.fromRGBO(68, 49, 122, 1.0),
              ),
              hintText: 'Senha',
              hintStyle: kHintTextStyle,
            ),
          ),
        ),
      ],
    );
  }

  Widget _btForgotPassword() {
    return Container(
      alignment: Alignment.centerRight,
      child: FlatButton(
        onPressed: () => print('Forgot Password Button Pressed'),
        padding: EdgeInsets.only(right: 0.0),
        child: Text(
          'Esqueci a senha',
          style: kLabelStyle,
        ),
      ),
    );
  }

  Widget _ckRememberMe() {
    return Container(
      height: 30.0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Row(
            children: [
              Theme(
                data: ThemeData(unselectedWidgetColor: Colors.white),
                child: Checkbox(
                  value: _rememberMe,
                  checkColor: Colors.green,
                  activeColor: Colors.white,
                  onChanged: (value) {
                    setState(() {
                      _rememberMe = value;
                    });
                  },
                ),
              ),
              Text(
                'Lembrar dados',
                style: kLabelStyle,
              ),
            ],
          ),
          Container(
            alignment: Alignment.centerRight,
            child: FlatButton(
              onPressed: () async {
                await _forgotPass(this.userLogin);
              },
              padding: EdgeInsets.only(right: 0.0),
              child: Text(
                'Esqueci a senha',
                style: kLabelStyle,
              ),
            ),
          )
        ],
      ),
    );
  }

  void _showGenericDialog(String title, String content) {
    showDialog(
        context: context,
        builder: (contextGlobal) {
          return AlertDialog(
            title: new Text(title),
            content: new Text(content),
          );
        });
  }

  Widget _btLogin() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 25.0),
      width: double.infinity,
      child: RaisedButton(
        elevation: 5.0,
        onPressed: () async {
          await _validateLogin(this.userLogin);
        },
        /*{
          FutureBuilder<ModelPerson>(
            future: getEvents(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                ModelPerson data = snapshot.data;
                Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(
                        builder: (context) => MyStatefulWidget(
                              person: data,
                            )));
              } else if (snapshot.hasError) {
                return clickAlert();
              }
              return CircularProgressIndicator();
            },
          );
        },

         */
        padding: EdgeInsets.all(15.0),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(30.0),
        ),
        color: Colors.white,
        child: Text(
          'LOGIN',
          style: TextStyle(
            color: Color(0xFF527DAA),
            letterSpacing: 1.5,
            fontSize: 18.0,
            fontWeight: FontWeight.bold,
            fontFamily: 'OpenSans',
          ),
        ),
      ),
    );
  }

  Widget _txSignInWith() {
    return Column(
      children: <Widget>[
        Text(
          '---',
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.w400,
          ),
        ),
        SizedBox(height: 20.0),
        Text(
          'Entrar com',
          style: kLabelStyle,
        ),
      ],
    );
  }

  Widget _btSocialLogin(Function onTap, AssetImage logo) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 60.0,
        width: 60.0,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: Colors.black26,
              offset: Offset(0, 2),
              blurRadius: 6.0,
            ),
          ],
          image: DecorationImage(
            image: logo,
          ),
        ),
      ),
    );
  }

  Widget _rowSocialLogin() {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 30.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          _btSocialLogin(
            () => print('Login com Facebook'),
            AssetImage(
              'assets/images/facebook.jpg',
            ),
          ),
          _btSocialLogin(
            () => print('Login com Google'),
            AssetImage(
              'assets/images/google.jpg',
            ),
          ),
        ],
      ),
    );
  }

  Widget _btSignup() {
    return GestureDetector(
      onTap: () => print('Sign Up Button Pressed'),
      child: RichText(
        text: TextSpan(
          children: [
            TextSpan(
              text: 'Quero ',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18.0,
                fontWeight: FontWeight.w400,
              ),
            ),
            TextSpan(
              text: 'Começar Agora',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18.0,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  }

  clickAlert() {
    showDialog(
        context: context,
        builder: (contextGlobal) {
          return AlertDialog(
            title: new Text("Erro"),
            content: new Text("Login ou senha incorreto"),
          );
        });
  }

  @override
  Widget build(BuildContext context) {
    return loading
        ? Loading()
        : Scaffold(
            body: AnnotatedRegion<SystemUiOverlayStyle>(
              value: SystemUiOverlayStyle.light,
              child: GestureDetector(
                onTap: () => FocusScope.of(context).unfocus(),
                child: Stack(
                  children: <Widget>[
                    Container(
                      height: double.infinity,
                      width: double.infinity,
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [
                            Color(0xFF44317A),
                            Color(0xFF5C42A3),
                            Color(0xFF785ACD),
                            Color(0xFF8067C4),
                          ],
                          stops: [0.1, 0.4, 0.7, 0.9],
                        ),
                      ),
                    ),
                    Container(
                      height: double.infinity,
                      width: double.infinity,
                      child: Center(
                        child: Padding(
                          padding: EdgeInsets.symmetric(
                            horizontal: 40.0,
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisSize: MainAxisSize.min,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Image.asset('assets/images/Jubo_Logo_White.png',
                                  width: 400),
                              SizedBox(height: 40.0),
                              _tfEmail(),
                              SizedBox(height: 10.0),
                              _tfPassword(),
                              SizedBox(height: 10.0),
                              //_btForgotPassword(),
                              _ckRememberMe(),
                              _btLogin(),
                              /*_txSignInWith(),
                      _rowSocialLogin(),*/
                            ],
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
          );
  }

  /*
  _login() async {
    var client = http.Client();
    var m = null;
    try {
      final response = await client.post(
          Uri.http(urlPrincipal, "/ws_jubo/service/v1/login"),
          body: {"login": "andrey", "pass": "123"});

      if (response.statusCode == 200) {
        var jsonResponse = json.decode(response.body)['data'][0];
        //m = jsonResponse.map((job) => new ModelPerson.fromJson(job));
        m = new ModelPerson.fromJson(jsonResponse);
      } else {
        throw Exception('Failed to load jobs from API');
      }
    } catch (Exception) {
      return m;
    }
    return m;
  }
*/

  _forgotPass(UserLogin user) async {
    AuthenticationService service = new AuthenticationService();

    try {
      if (userLogin.login != null) {
        if (userLogin.login.isNotEmpty) {
          setState(() => loading = true);
          //updateProgress('Validando...');
          if (await service.forgotPass(user.login)) {
            setState(() => loading = false);
            showAlertDialog(context, 'JuBo', "Email enviado com nova senha!");
          } else {
            setState(() => loading = false);
            showAlertDialog(context, 'JuBo', "Problemas ao enviar Email!");
          }
        } else {
          setState(() => loading = false);
          showAlertDialog(context, 'JuBo', "Informe o Email!");
        }
      } else {
        setState(() => loading = false);
        showAlertDialog(context, 'JuBo', "Informe o Email!");
      }
    } catch (Exception) {
      setState(() => loading = false);
      showAlertDialog(context, 'JuBo', "Problemas ao enviar Email!");
    }
  }

  _validateLogin(UserLogin user) async {
    /* if (_key.currentState.validate()) {
      _key.currentState.save();*/
    //showProgress(context, 'Conectando...', true);
    //await new Future.delayed(const Duration(seconds: 1));
    var m = null;

    AuthenticationService service = new AuthenticationService();

    try {
      setState(() => loading = true);
      //updateProgress('Validando...');
      await service.login(user.login, user.pass, _rememberMe);

      //hideProgress();

      Navigator.pushReplacement(
          context,
          MaterialPageRoute(
              builder: (context) => MyStatefulWidget(
                    selectedIndex: 0,
                  )));
      //setState(() => loading = false);
    } catch (Exception) {
      setState(() => loading = false);
      //hideProgress();
      showAlertDialog(context, 'JuBo', "Login ou Senha inválido");
    }
/*
    if (m != null) {
      hideProgress();
    }

 */
  }
}

//antes de mudar
/*
_validateLogin(UserLogin user) async {
  /* if (_key.currentState.validate()) {
      _key.currentState.save();*/
  showProgress(context, 'Conectando...', true);

  var m = null;

  AuthenticationService service = new AuthenticationService();

  try {

    final response = await http.post("$urlPrincipal/ws_jubo/service/v1/login",
      body: user.toJson(),
    );
    updateProgress('Validando...');
    if (response.statusCode == 200) {
      var jsonResponse = json.decode(response.body)['data'][0];
      //m = jsonResponse.map((job) => new ModelPerson.fromJson(job));
      m = new ModelPerson.fromJson(jsonResponse);
    } else {
      hideProgress();
      showAlertDialog(context, 'Failed',
          "Problemas ao conectar ao servidor\n${response.statusCode}");
      /*
        Navigator.pushReplacement(
            context,
            MaterialPageRoute(
                builder: (context) => MyStatefulWidget(
                  selectedIndex: 0,
                  person: m,
                )));*/
    }
  } catch (Exception) {
    hideProgress();
    showAlertDialog(context, 'Failed', "Login ou Senha inválido");
  }

  if (m != null) {
    hideProgress();
    Navigator.pushReplacement(
        context,
        MaterialPageRoute(
            builder: (context) => MyStatefulWidget(
              selectedIndex: 0,
              person: m,
            )));
  }

  //var profilePicUrl = '';
  //await new Future.delayed(const Duration(seconds : 2));
  /*
      try {
        auth.UserCredential result = await auth.FirebaseAuth.instance
            .createUserWithEmailAndPassword(
                email: email.trim(), password: password.trim());
                */
  /*if (_image != null) {
        updateProgress('Uploading image, Please wait...');

        final base64Image = await _image.readAsBytes();
        print(base64Encode(base64Image).length);

        //profilePicUrl = await FireStoreUtils()
        //    .uploadUserImageToFireStorage(_image, result.user.uid);
      }*/
  /*
        User user = User(
            email: email,
            firstName: firstName,
            phoneNumber: mobile,
            userID: result.user.uid,
            active: true,
            lastName: lastName,
            profilePictureURL: profilePicUrl);
        await FireStoreUtils.firestore
            .collection(USERS)
            .doc(result.user.uid)
            .set(user.toJson());
        hideProgress();
        MyAppState.currentUser = user;
        pushAndRemoveUntil(context, HomeScreen(user: user), false);
      } on auth.FirebaseAuthException catch (error) {
        hideProgress();
        String message = 'Couldn\'t sign up';
        switch (error.code) {
          case 'email-already-in-use':
            message = 'Email address already in use';
            break;
          case 'invalid-email':
            message = 'validEmail';
            break;
          case 'operation-not-allowed':
            message = 'Email/password accounts are not enabled';
            break;
          case 'weak-password':
            message = 'password is too weak.';
            break;
          case 'too-many-requests':
            message = 'Too many requests, '
                'Please try again later.';
            break;
        }
        showAlertDialog(context, 'Failed', message);
        print(error.toString());
      } catch (e) {
        print('_SignUpState._sendToServer $e');
        hideProgress();
        showAlertDialog(context, 'Failed', 'Couldn\'t sign up');
      }

      */

  /*
    } else {
      setState(() {
        _validate = AutovalidateMode.onUserInteraction;
      });
    }*/
}
}
*/

class UserLogin {
  String login;
  String pass;

  UserLogin({this.login, this.pass});

  String toJson() => jsonEncode({'login': this.login, 'pass': this.pass});
}
