import 'dart:convert';

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

class PreLogin extends StatefulWidget {
  @override
  _PreLoginScreenState createState() => _PreLoginScreenState();
}

class _PreLoginScreenState extends State<PreLogin> {
  @override
  void initState() {
    super.initState();
  }

  isLogged() async {
    try {
      //await InstanceDB.connect();
      //await Future.delayed(Duration(seconds: 1));

      AuthenticationService auth = new AuthenticationService();

      bool isAuth = await auth.isAuth();

      if (isAuth) {
        Navigator.pushReplacement(
            context,
            MaterialPageRoute(
                builder: (context) => MyStatefulWidget(selectedIndex: 0)));
      } else {
        Navigator.pushReplacement(
            context, MaterialPageRoute(builder: (context) => Login()));
      }
    } catch (e) {
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('Erro'),
            content: Text(e.toString()),
            actions: <Widget>[
              FlatButton(
                child: Text('Fechar'),
                onPressed: () => Navigator.of(context).pop(),
              ),
            ],
          );
        },
      );
    }
  }

  Widget _buildLoginBtn() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 15.0),
      width: double.infinity,
      child: RaisedButton(
        elevation: 5.0,
        onPressed: isLogged,
        /*{
          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(25.0),
        ),
        color: Colors.white,
        child: Text(
          'Entrar',
          style: TextStyle(
            color: Color(0xFF5C42A3),
            letterSpacing: 1.5,
            fontSize: 16.0,
            fontWeight: FontWeight.bold,
            fontFamily: 'OpenSans',
          ),
        ),
      ),
    );
  }

  Widget _buildCreateBtn() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 15.0),
      width: double.infinity,
      child: ElevatedButton(
        //elevation: 5.0,
        onPressed: () {
          Navigator.pushReplacement(
              context, MaterialPageRoute(builder: (context) => SignUpScreen()));
        },

        style: ElevatedButton.styleFrom(
            padding: EdgeInsets.all(15.0),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(25.0),
            ),
            primary: Colors.transparent,
            elevation: 0.0,
            side: BorderSide(
              color: Colors.white,
            )),
        child: Text(
          'Começar',
          style: TextStyle(
            color: Colors.white,
            letterSpacing: 1.5,
            fontSize: 16.0,
            fontWeight: FontWeight.bold,
            fontFamily: 'OpenSans',
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return 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(0xFF8067C4),
                      Color(0xFF785ACD),
                      Color(0xFF5C42A3),
                      Color(0xFF44317A),
                    ],
                    stops: [0.1, 0.4, 0.7, 0.9],
                  ),
                ),
              ),
              Container(
                height: double.infinity,
                child: SingleChildScrollView(
                  physics: AlwaysScrollableScrollPhysics(),
                  padding: EdgeInsets.symmetric(
                    horizontal: 40.0,
                    vertical: 120.0,
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      SizedBox(height: 70.0),
                      Image.asset('assets/images/Jubo_Logo_White.png',
                          width: 400),
                      SizedBox(height: 40.0),
                      _buildLoginBtn(),
                      _buildCreateBtn(),

                      //_buildSocialBtnRow(),
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  Future<ModelPerson> getEvents() async {
    final response = await http.post(
        Uri.http(urlPrincipal, "/ws_jubo/service/v1/login"),
        body: {"login": "andrey", "pass": "123"});

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

class UserLogin {
  String login;
  String pass;

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

  Map<String, dynamic> toJson() => {"login": this.login, "pass": this.pass};
}
