import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'main.dart';
import 'Util/Prefs.dart';


class LoginPage extends StatefulWidget {
  LoginPage({Key key}) : super(key: key);
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final userCon = new TextEditingController();
  final passCon = new TextEditingController();
  final hostAddress = new TextEditingController();
  List<dynamic> cabangDrop = [];
  String selected;



  Login()async{
    util.showLoading(context);
    var result = await util.JsonDataPostRaw({"User":userCon.text,"Pass":passCon.text}, '${prefs.getString(keyClass.hostAddress)??'https://unitstocksbackend.thamringroup.web.id'}/login');
    if(result['STATUS']==1){
      prefs.setString(keyClass.user_id, result['DATA'][keyClass.user_id]);
      prefs.setString(keyClass.company, result['DATA'][keyClass.company]);
      prefs.setBool(keyClass.logged_in, true);
      var cabangList = await util.JsonDataPostRaw({"company":prefs.getString(keyClass.company),"User":prefs.getString(keyClass.user_id)}, '${prefs.getString(keyClass.hostAddress)??'https://unitstocksbackend.thamringroup.web.id'}/getCabangByUser');
      Navigator.pop(context);
      if(cabangList['STATUS']==1){
        cabangDrop = cabangList['DATA'];
        print(cabangList);
        selected = cabangDrop[0]['RETURN_VALUE'];
        setState(() {
        });
        FocusScope.of(context).requestFocus(new FocusNode());
      }
      else{
        util.showFlushbar(context, cabangList['DATA'],color: Colors.red);
      }
    }
    else{
      Navigator.pop(context);
      util.showFlushbar(context, result['DATA'],color: Colors.red);
    }
  }

  @override
  Widget build(BuildContext context) {
//    if(prefs.getBool(keyClass.logged_in)==null||!prefs.getBool(keyClass.logged_in)){
      return Scaffold(
        body: WillPopScope(
          onWillPop: ()async{
            if(prefs.getBool(keyClass.logged_in)==null||!prefs.getBool(keyClass.logged_in)){
              await showDialog(context: context,builder: (context)=>AlertDialog(
                content: Text('Exit the app?'),
                actions: <Widget>[
                  FlatButton(
                    child: Text('Exit'),
                    onPressed: ()async{
                      Navigator.pop(context);
                      await locationStream?.cancel();
                      exit(0);
                    },
                  ),
                  FlatButton(
                    child: Text('Cancel'),
                    onPressed: (){
                      Navigator.pop(context);
                    },
                  )

                ],
              ));
            }
            else{
              setState(() {
                prefs.setBool(keyClass.logged_in, false);
                prefs.remove(keyClass.cabang_id);
                prefs.remove(keyClass.company);
                prefs.remove(keyClass.user_id);
              });
            }
            return false;
          },
          child: Container(
            decoration: BoxDecoration(
                color: Colors.white
            ),
            child: Stack(
              children: <Widget>[
                Positioned.fill(
                  child: Column(
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: Container(),
                      ),
                      Expanded(
                        flex: 3,
                        child: InkWell(
                          onLongPress: ()async{
                            hostAddress.text = prefs.getString(keyClass.hostAddress)??'https://unitstocksbackend.thamringroup.web.id';
                            await showDialog(context: context,builder: (context)=>AlertDialog(
                              title: Text('Set IP Address'),
                              content: TextField(
                                controller: hostAddress,
                                onSubmitted: (value){
                                  prefs.setString(keyClass.hostAddress,(value=='')?'https://unitstocksbackend.thamringroup.web.id':value);
                                  Navigator.pop(context);
                                },
                              ),
                              actions: <Widget>[
                                FlatButton(
                                  child: Text('OK'),
                                  onPressed: (){
                                    prefs.setString(keyClass.hostAddress,(hostAddress.text=='')?'https://unitstocksbackend.thamringroup.web.id':hostAddress.text);
                                    Navigator.pop(context);
                                  },
                                )
                              ],
                            ));
                          },
                          child: Column(
                            children: <Widget>[
                              Container(child: Icon(Icons.input,size: 150,color: Colors.indigo,),),
                              Text('Login',style: TextStyle(fontSize: 25,color: Colors.indigo,fontWeight: FontWeight.bold),),
                            ],
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 3,
                        child: Column(
                          children: <Widget>[
                            Container(
                              width: MediaQuery.of(context).size.width*0.8,
                              child: TextFormField(
                                controller: userCon,
                                style: TextStyle(color: Colors.indigo,fontSize: 16),
                                decoration: InputDecoration(
                                    hintText: 'User ID',
                                    contentPadding:EdgeInsets.only(left: 30,right: 30,top: 20,bottom: 20),
                                    hintStyle: TextStyle(fontSize: 16,color: Colors.indigo.withOpacity(0.7)),
                                    focusedBorder: OutlineInputBorder(
                                        borderSide: BorderSide(
                                            color: Colors.indigo,
                                            width: 2),
                                        borderRadius: BorderRadius.circular(100)
                                    ),
                                    enabledBorder: OutlineInputBorder(
                                        borderSide: BorderSide(
                                            color: Colors.indigo.withOpacity(0.5),
                                            width: 0.5),
                                        borderRadius: BorderRadius.circular(100)
                                    )
                                ),
                              ),
                            ),
                            SizedBox(height: 15,),
                            Container(
                              width: MediaQuery.of(context).size.width*0.8,
                              child: TextFormField(
                                obscureText: true,
                                controller: passCon,
                                style: TextStyle(color: Colors.indigo,fontSize: 16),
                                decoration: InputDecoration(
                                    contentPadding:EdgeInsets.only(left: 30,right: 30,top: 20,bottom: 20),
                                    hintText: 'Password',
                                    hintStyle: TextStyle(fontSize: 16,color: Colors.indigo.withOpacity(0.7)),
                                    focusedBorder: OutlineInputBorder(
                                        borderSide: BorderSide(
                                            color: Colors.indigo,
                                            width: 2),
                                        borderRadius: BorderRadius.circular(100)
                                    ),
                                    enabledBorder: OutlineInputBorder(
                                        borderSide: BorderSide(
                                            color: Colors.indigo.withOpacity(0.5),
                                            width: 0.5),
                                        borderRadius: BorderRadius.circular(100)
                                    )
                                ),
                              ),
                            ),
                            SizedBox(height: 30,),
                            FlatButton(
                              onPressed: Login,
                              padding: EdgeInsets.all(15),
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(100.0),
                                  side: BorderSide(color: Colors.indigo)
                              ),
                              color: Colors.indigo,
                              child: Container(width: MediaQuery.of(context).size.width*0.7,child: Text('Login',textAlign: TextAlign.center,style: TextStyle(color: Colors.white,fontSize: 21),)),
                            )
                          ],
                        ),
                      ),
//            Expanded(
//              flex: 3,
//              child: Container(color: Colors.yellow,),
//            ),
                    ],
                  ),
                ),
                (prefs.getBool(keyClass.logged_in)==null||!prefs.getBool(keyClass.logged_in))
                    ?Container()
                    :Positioned.fill(
                    child: Container(
                      color: Colors.white.withOpacity(0.9),
                      child: Center(
                        child: Container(
                          decoration: BoxDecoration(
                              color: Colors.white,
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.grey.withOpacity(0.5),
                                  spreadRadius: 5,
                                  blurRadius: 7,
                                  offset: Offset(0, 3), // changes position of shadow
                                ),
                              ],
                              borderRadius: BorderRadius.circular(5)
                          ),
                          height: MediaQuery.of(context).size.height/3.2,
                          width: MediaQuery.of(context).size.width*0.75,
                          child: Column(
                            children: <Widget>[
                              Flexible(
                                flex:3,
                                child: Container(
                                  padding: EdgeInsets.only(top:10,left: 10,right: 10),
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(
//                          color: Colors.indigo,
                                      borderRadius: BorderRadius.only(topLeft: Radius.circular(5),topRight: Radius.circular(5))
                                  ),
                                  child: Column(
                                    mainAxisSize: MainAxisSize.min,
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: <Widget>[
                                      Icon(Icons.business,size: 70,color: Colors.indigo,),
                                      SizedBox(height: 5,),
                                      Text('Pilih Cabang',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16,color: Colors.indigo),)
                                    ],
                                  ),
                                ),
                              ),
                              Flexible(
                                flex: 1,
                                child: Container(
                                  padding: EdgeInsets.only(left: 20,right: 20),
                                  alignment: Alignment.centerLeft,
                                  child: Theme(
                                    data: ThemeData(
                                        canvasColor: Colors.white,
                                        primaryColor: Colors.indigo,
                                        accentColor: Colors.indigo,
                                        hintColor: Colors.indigo
                                    ),
                                    child: DropdownButtonFormField(
                                      style: TextStyle(color: Colors.black.withOpacity(0.6),fontWeight: FontWeight.w500,fontSize: 14,),
                                      decoration: InputDecoration(
                                        contentPadding: EdgeInsets.all(8.0),
                                      ),
                                      value: selected,
                                      onChanged: (value){
                                        setState(() {
                                          selected = value;
                                        });
                                      },
                                      items: cabangDrop.map<DropdownMenuItem<dynamic>>((item)=>DropdownMenuItem(
                                        value: item['RETURN_VALUE'],
                                        child: Text(item["DISPLAY_VALUE"]),
                                      )).toList(),
                                    ),
                                  ),
                                ),
                              ),
                              Flexible(
                                flex: 1,
                                child: Container(
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    children: <Widget>[
                                      ButtonTheme(
                                        minWidth: 10,
                                        child: FlatButton(
                                          onPressed: (){
                                            prefs.setString(keyClass.cabang_id, selected);
                                            Navigator.pushNamed(context, '/home');
                                          },
                                          child: Text('Set',style: TextStyle(color: Colors.indigo),),
                                        ),
                                      ),
                                      FlatButton(
                                        onPressed: (){
                                          setState(() {
                                            prefs.setBool(keyClass.logged_in, false);
                                            prefs.remove(keyClass.cabang_id);
                                            prefs.remove(keyClass.company);
                                            prefs.remove(keyClass.user_id);
                                          });
                                        },
                                        child: Text('Cancel',style: TextStyle(color: Colors.indigo)),
                                      )
                                    ],
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    )
                ),
              ],
            ),
          ),
        ),
      );
//    }
//    else{
//      return WillPopScope(
//        onWillPop: ()async{
//          setState(() {
//            prefs.setBool(keyClass.logged_in, false);
//            prefs.remove(keyClass.cabang_id);
//            prefs.remove(keyClass.company);
//            prefs.remove(keyClass.user_id);
//          });
//          return false;
//        },
//        child: Material(
//          child: Container(
//            color: Colors.grey.withOpacity(0.7),
//            child: Center(
//              child: Container(
//                decoration: BoxDecoration(
//                color: Colors.white,
//                  borderRadius: BorderRadius.circular(5)
//                ),
//                height: MediaQuery.of(context).size.height/3.2,
//                width: MediaQuery.of(context).size.width*0.75,
//                child: Column(
//                  children: <Widget>[
//                    Flexible(
//                      flex:3,
//                      child: Container(
//                        padding: EdgeInsets.only(top:10,left: 10,right: 10),
//                        alignment: Alignment.center,
//                        decoration: BoxDecoration(
////                          color: Colors.indigo,
//                          borderRadius: BorderRadius.only(topLeft: Radius.circular(5),topRight: Radius.circular(5))
//                        ),
//                        child: Column(
//                          mainAxisSize: MainAxisSize.min,
//                          crossAxisAlignment: CrossAxisAlignment.center,
//                          children: <Widget>[
//                            Icon(Icons.business,size: 70,color: Colors.indigo,),
//                            SizedBox(height: 5,),
//                            Text('Pilih Cabang',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16,color: Colors.indigo),)
//                          ],
//                        ),
//                      ),
//                    ),
//                    Flexible(
//                      flex: 1,
//                      child: Container(
//                        padding: EdgeInsets.only(left: 20,right: 20),
//                        alignment: Alignment.centerLeft,
//                        child: Theme(
//                          data: ThemeData(
//                              canvasColor: Colors.white,
//                              primaryColor: Colors.indigo,
//                              accentColor: Colors.indigo,
//                              hintColor: Colors.indigo
//                          ),
//                          child: DropdownButtonFormField(
//                            style: TextStyle(color: Colors.black.withOpacity(0.6),fontWeight: FontWeight.w500,fontSize: 14,),
//                            decoration: InputDecoration(
//                              contentPadding: EdgeInsets.all(8.0),
//                               ),
//                            value: selected,
//                            onChanged: (value){
//                              setState(() {
//                                selected = value;
//                              });
//                            },
//                            items: cabangDrop.map<DropdownMenuItem<dynamic>>((item)=>DropdownMenuItem(
//                              value: item['RETURN_VALUE'],
//                              child: Text(item["DISPLAY_VALUE"]),
//                            )).toList(),
//                          ),
//                        ),
//                      ),
//                    ),
//                    Flexible(
//                      flex: 1,
//                      child: Container(
//                        child: Row(
//                          mainAxisAlignment: MainAxisAlignment.end,
//                          children: <Widget>[
//                            ButtonTheme(
//                              minWidth: 10,
//                              child: FlatButton(
//                                onPressed: (){
//                                  prefs.setString(keyClass.cabang_id, selected);
//                                  Navigator.pushNamed(context, '/home');
//                                },
//                                child: Text('Set',style: TextStyle(color: Colors.indigo),),
//                              ),
//                            ),
//                            FlatButton(
//                              onPressed: (){
//                                setState(() {
//                                  prefs.setBool(keyClass.logged_in, false);
//                                  prefs.remove(keyClass.cabang_id);
//                                  prefs.remove(keyClass.company);
//                                  prefs.remove(keyClass.user_id);
//                                });
//                              },
//                              child: Text('Cancel',style: TextStyle(color: Colors.indigo)),
//                            )
//                          ],
//                        ),
//                      ),
//                    )
//                  ],
//                ),
//              ),
//            ),
//          ),
//        ),
//      );
//    }
  }
}