import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:rkm/screens/home_screen.dart';
import 'package:rkm/screens/login/sync_login_screen.dart';
import 'package:rkm/config/color_palette.dart';
import 'package:rkm/config/const_variable.dart';
import 'package:rkm/widgets/button_default.dart';
import 'package:rkm/widgets/input_text.dart';
import 'package:rkm/widgets/text_default.dart';
import '../../controllers/main_controllers.dart';
import '../../service/api/api_data_load.dart';
import '../../service/db/db_sqlite_load.dart';
class LoginSavedScreen extends StatefulWidget {
  List listControl;

  LoginSavedScreen({
    required this.listControl,
  });

  @override
  State<LoginSavedScreen> createState() => _LoginSavedScreenState();
}

class _LoginSavedScreenState extends State<LoginSavedScreen> {

  var inputUser = TextEditingController();
  var inputPassword = TextEditingController();
  String error = '';
  String? now;
  bool validatorDropDown= false;
  int contLogo = 0;
  bool loading = false;
  String urlAPI='';
  String mode = '';
  String nameCityApi = '';
  String nameCityFront = '';
  int codCity = 0;
  int codCityIbge = 0;
  String  codState = '';

  recupDB()async{
    await DbSqliteLoad().intialDB().then((db)async{
      List list = await db.query('ARGS');
      urlAPI = list[0]['URLAPI'];
      mode = list[0]['MODE'];
      nameCityApi = list[0]['NAME_CITY_API'];
      nameCityFront = list[0]['NAME_CITY_FRONT'];
      inputUser.text = list[0]['USER'];
      inputPassword.text = list[0]['PASSWORD'];
      codCity = list[0]['COD_CITY'];
      codState = list[0]['COD_STATE'];
      codCityIbge = list[0]['COD_IBGE'];
    });
    setState(() {});
  }

  checkLogin()async{
    if(inputUser.text.isNotEmpty && inputPassword.text.isNotEmpty && inputUser.text.length>3 && inputPassword.text.length>3){
      setState(() {
        error = '';
        loading = true;
      });
        await ApiDataLoad().apiConect(urlAPI,mode,nameCityApi,inputUser.text).then((response) async {
          if(inputUser.text == inputPassword.text || response['bloqueio']==1){
            setState(() {
              error = 'Usuário bloqueado/senha incorreta';
            });
          }else if(response['status']==0) {
            setState(() {
              error = 'Usuário não encontrado';
            });
          }else if(response['status']==1) {
            setState((){
              error = '';
            });
            //verificar se a criptografia identificou se a senha está correta
            if(MainControllers().encrypt(inputPassword.text,response['userPass']) == response['userPass']){
              // print(EncryptPassword().encrypt(inputPassword.text,response['userPass']));
              DbSqliteLoad().updateArgs(mode, inputUser.text, inputPassword.text).then((value){
                setState(() {
                  loading = false;
                });
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => HomeScreen()),
                );
              });
            }
          }
        });
    }else{
      setState(() {
        error = 'Usuário/senha inválido(s)';
      });
    }
  }

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

  @override
  Widget build(BuildContext context) {

    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: TextDefault(text: 'RKM AB - Login',fontSize: ConstVariable().fontSizeTitleAppBar,color: ColorPalette.white),
        actions: [
          ButtonDefault(
            width: width*0.35,
            borderColor: ColorPalette.appBar,
            textColor: ColorPalette.white,
            title: 'Sincronizar outra unidade',
            onPressed: (){
              Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => SyncLoginScreen()),
              );
            }
          )
        ],
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.only(top: height*0.1),
          width: width,
          height: height,
          decoration: ConstVariable().backgroundGradient,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Image.asset('assets/images/logo.PNG',width: width*0.4),
              mode == 'homologacao'?Image.asset('assets/images/homologacao.png',width: width*0.4):Container(),
              mode == 'desenvolvimento'?Image.asset('assets/images/desenvolvimento.png',width: width*0.4):Container(),
              SizedBox(height: 10),
              loading?Center(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset('assets/images/loading.gif'),
                    SizedBox(height: 10),
                    TextDefault(text: 'Carregando dados...',color: ColorPalette.black54,fontSize: 20,fontWeigth: FontWeight.bold,)
                  ],
                ),
              ):Form(
                autovalidateMode: AutovalidateMode.onUserInteraction,
                child: Container(
                  width: width*0.6,
                  height: height*0.2,
                  child: ListView(
                    children: [
                      InputText(
                        hint: 'Usuário',
                        label: inputUser.text.isNotEmpty?'':'Usuário',
                        controller: inputUser,
                        width: width*0.6,
                        colorBorder: Colors.white,
                        onChanged: (v)=>setState((){}),
                      ),
                      InputText(
                        hint: 'Senha',
                        label: inputPassword.text.isNotEmpty?'':'Senha',
                        obscure: true,
                        controller: inputPassword,
                        width: width*0.6,
                        colorBorder: Colors.white,
                        onChanged: (v)=>setState((){}),
                      ),
                    ],
                  ),
                ),
              ),
              loading?Container():ButtonDefault(
                onPressed: ()=>checkLogin(),
                title: 'Entrar',
                width: width*0.6,
              ),
              SizedBox(height: 10),
              TextDefault(text: error,color: ColorPalette.red),
              widget.listControl.length==0?Container():Container(
                width: width*0.6,
                child: TextDefault(
                  text: 'Última sincronização: '+DateFormat('dd/MM/yyyy kk:mm:ss').format(DateTime.parse(widget.listControl[0]['ULTIMA_SINCRONIZACAO'])),
                  fontWeigth: FontWeight.bold,
                  color: Colors.black,
                  textAlign: TextAlign.center,
                  maxLines: 2,
                ),
              ),
              widget.listControl.length==0?Container():Container(
                padding: EdgeInsets.symmetric(vertical: 5),
                width: width*0.6,
                child: TextDefault(
                  text: 'Unidade: '+widget.listControl[0]['NOME_UNIDADE'].toString(),
                  fontWeigth: FontWeight.bold,
                  color: Colors.black,
                  textAlign: TextAlign.center,
                  maxLines: 2,
                ),
              ),
              widget.listControl.length==0?Container():Container(
                padding: EdgeInsets.symmetric(vertical: 5),
                width: width*0.6,
                child: TextDefault(
                  text: 'Competência: '+widget.listControl[0]['COMPETENCIA'].toString(),
                  fontWeigth: FontWeight.bold,
                  color: Colors.black,
                  textAlign: TextAlign.center,
                  maxLines: 2,
                ),
              ),
              widget.listControl.length==0?Container():Container(
                padding: EdgeInsets.symmetric(vertical: 5),
                width: width*0.6,
                child: TextDefault(
                  text: 'Área: '+widget.listControl[0]['AREA'].toString()+' - Microárea: '+widget.listControl[0]['MICROAREA'].toString(),
                  fontWeigth: FontWeight.bold,
                  color: Colors.black,
                  textAlign: TextAlign.center,
                  maxLines: 2,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
