import 'package:flutter/material.dart';
import 'package:rkm/controllers/main_controllers.dart';
import 'package:rkm/service/api/url_api_const.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/dropdown_button_city.dart';
import 'package:rkm/widgets/input_text.dart';
import 'package:rkm/widgets/text_default.dart';
import '../../service/api/api_data_load.dart';
import '../../service/db/db_sqlite_load.dart';
import '../../service/shared_preferences/shared_preferences_service.dart';
import '../load_init_screen.dart';
class LoginLoadScreen extends StatefulWidget {
  const LoginLoadScreen({Key? key}) : super(key: key);

  @override
  State<LoginLoadScreen> createState() => _LoginLoadScreenState();
}

class _LoginLoadScreenState extends State<LoginLoadScreen> {

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

  final PrefService _prefService = PrefService();
  checkLogin()async{
    if(inputUser.text.isNotEmpty && inputPassword.text.isNotEmpty && inputUser.text.length>3 && inputPassword.text.length>3){
      if(selectCity!=null){
        _prefService.createCacheModel(inputUser.text,inputPassword.text,selectCity!,mode);
          setState(() {
            error = '';
            loading = true;
            for(int i=0;ConstVariable().itensCity.length > i;i++){
              if(ConstVariable().itensCity[i].nameCityFront == selectCity!){
                nameCityApi = ConstVariable().itensCity[i].nameCityApi;
                nameCityFront = ConstVariable().itensCity[i].nameCityFront;
                codCityIbge = ConstVariable().itensCity[i].codCityIbge;
                codCity = ConstVariable().itensCity[i].codCity;
                codState = ConstVariable().itensCity[i].codState;
              }
            }
          });
            await ApiDataLoad().apiConect(urlAPI,mode,nameCityApi,inputUser.text).then((response) async {
              print("erre : "+response.toString());
              if(response == 'Erro' || response.toString() == 'Error: -902 - I/O error during "open" operation for file "/bases/conectasus/extrema/SISTEMA.FDB" Error while trying to open file No such file or directory'){
                setState(() {
                  loading = false;
                  error = 'Erro na conexão!Verifique sua internet\n ou a cidade que está selecionada!';
                });
              }else if(inputUser.text == inputPassword.text || response['bloqueio']==1){
                setState(() {
                  loading = false;
                  error = 'Usuário bloqueado/usuário e/ou senha incorreta';
                });
              }else if(response['status']==0) {
                setState(() {
                  loading = false;
                  error = 'Usuário não encontrado';
                });
              }else if(response['status']==1) {
                print('aqui 1');
                print(response);
                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']));
                  setState(() {
                    loading = false;
                  });
                  await DbSqliteLoad().deleteLoad().then((_)async {
                    DbSqliteLoad().saveArgs(
                        mode,
                        inputUser.text,
                        inputPassword.text,
                        urlAPI,
                        codCity,
                        nameCityApi,
                        nameCityFront,
                        codState,
                        codCityIbge).then((value) {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => LoadInitScreen()),
                      );
                    });
                  });
                }else{
                  setState(() {
                    loading = false;
                    error = 'Usuário bloqueado/senha incorreta';
                  });
                }
              }else{
                setState(() {
                  loading = false;
                  error = 'Falha de conexão com API';
                });
              }
            });
      }else{
        setState(() {
          error = 'Selecione sua cidade';
        });
      }
    }else{
      setState(() {
        error = 'Usuário/senha inválido(s)';
      });
    }
  }

  @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 - Carga Inicial',fontSize: ConstVariable().fontSizeTitleAppBar,color: ColorPalette.white),
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.only(top: height*0.2),
          width: width,
          height: height,
          decoration: ConstVariable().backgroundGradient,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              GestureDetector(
                onTap: loading?null:()=>setState((){
                  contLogo++;
                  if(contLogo>=5 && contLogo<=10){
                    mode = UrlApiConst.ModeHomologacao;
                    urlAPI = UrlApiConst.ApiUrlHomologacao;
                  }
                  if(contLogo>10){
                    mode = UrlApiConst.ModeDesenvolvimento;
                    urlAPI = UrlApiConst.ApiUrlDesenvolvimento;
                    if(contLogo==15){
                      contLogo=0;
                      mode =  UrlApiConst.ModeOnline;
                      urlAPI = UrlApiConst.ApiUrlOnline;
                    }
                  }
                }),
                child: 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.3,
                  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((){}),
                      ),
                      DropDownButtonCity(
                        error: 'Campo obrigatório',
                        validator: validatorDropDown,
                        select: selectCity,
                        onChanged: (value){
                          setState(() {
                            selectCity = value!;
                            validatorDropDown = true;
                          });
                        },
                      ),
                    ],
                  ),
                ),
              ),
              loading?Container():ButtonDefault(
                onPressed: ()=>checkLogin(),
                title: 'Carga Inicial',
                width: width*0.6,
              ),
              SizedBox(height: 10),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 20.0),
                child: TextDefault(text: error,color: ColorPalette.red,maxLines: 3),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
