import 'package:flutter/material.dart';
import 'package:rkm/screens/sync_init_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/dropdown_button_default.dart';
import 'package:rkm/widgets/input_text.dart';
import 'package:rkm/widgets/text_default.dart';
import 'package:sqflite/sqflite.dart';
import '../../controllers/main_controllers.dart';
import '../../service/api/api_data_load.dart';
import '../../service/db/db_sqlite_load.dart';
import '../../service/shared_preferences/shared_preferences_service.dart';
class SyncLoginScreen extends StatefulWidget {

  @override
  State<SyncLoginScreen> createState() => _SyncLoginScreenState();
}

class _SyncLoginScreenState extends State<SyncLoginScreen> {

  var inputUser = TextEditingController();
  var inputPassword = TextEditingController();
  String error = '';
  String? now;
  String? selectUnit;
  String? selectTeam;
  bool validatorDropDown= false;
  bool citizenOutArea = false;
  int contLogo = 0;
  String mode = '';
  String urlAPI = '';
  String nameCityApi = '';
  bool loading = false;
  List<String> listUnit=[];
  List searchUnitCodList=[];
  List<String> listTeam = [];
  String idUnidade ='';
  String idUsuario ='1';

  final PrefService _prefService = PrefService();

  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'];
      inputUser.text = list[0]['USER'];
      inputPassword.text = list[0]['PASSWORD'];
    });
    setState(() {});
  }

  checkLogin()async{
    if(inputUser.text.isNotEmpty && inputPassword.text.isNotEmpty && inputUser.text.length>3 && inputPassword.text.length>3){
      if(selectUnit!=null){
        if(selectTeam!=null){
          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 = '';
              });
              if(MainControllers().encrypt(inputPassword.text,response['userPass']) == response['userPass']){
                setState(() {
                  loading = false;
                });
                _prefService.createCacheSync(selectTeam!, citizenOutArea).then((value){
                  DbSqliteLoad().updateArgs(mode, inputUser.text, inputPassword.text).then((value) {
                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => SyncInitScreen()),
                    );
                  });
                });
              }
            }
          });
        }else{
          setState(() {
            error = 'Selecione sua equipe';
          });
        }
      }else{
        setState(() {
          error = 'Selecione sua unidade';
        });
      }
    }else{
      setState(() {
        error = 'Usuário/senha inválido(s)';
      });
    }
  }

  @override
  void initState() {
    super.initState();
    recupDB();
    getUnit();
    // getUser();
  }
  getUser(){
    _prefService.readCacheIdUsuario('idUsuario').then((value){
      if(value != null){
        idUsuario = value;
      }
    });
  }

  getUnit()async{
    Database db = await DbSqliteLoad().intialDB();
    var query = "SELECT * FROM UNIDADES";
    List list = await db.rawQuery(query);
    // print("SELECT * FROM UNIDADES");
    // print(await db.rawQuery("SELECT * FROM UNIDADES"));
    for(int i=0; list.length > i;i++){
      listUnit.add(list[i]['NOME_UNIDADE']);
      searchUnitCodList.add(list[i]['ID_UNIDADE']);
    }
    setState(() {});
  }

  getTeam()async{
    Database db = await DbSqliteLoad().intialDB();
    for(int i=0; listUnit.length > i;i++){
      if(listUnit[i] == selectUnit){
          idUnidade = searchUnitCodList[i].toString();
          _prefService.createCacheUnidade(idUnidade,selectUnit!);
      }
    }
    if(idUnidade!=''){
      print('idUnidade');
      print(idUnidade);
      print('idUsuario');
      print(idUsuario);
      var query = "SELECT * FROM EQUIPES JOIN PROFISSIONAIS_EQUIPE ON PROFISSIONAIS_EQUIPE.ID_EQUIPE = EQUIPES.ID_EQUIPE WHERE ID_UNIDADE = $idUnidade AND ID_PROFISSIONAL = $idUsuario";
      List list = await db.rawQuery(query);
      listTeam.clear();
      for(int i=0; list.length > i;i++){
        listTeam.add('INE: ${list[i]['INE']} / Área: ${list[i]['AREA']} - Microárea : ${list[i]['MICROAREA']}');
      }
      setState(() {});
    }
    print('listTeam');
    print(listTeam);
  }

  @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 - Sincronização de Unidade',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: [
              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.35,
                  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((){}),
                      ),
                      DropDownButtonDefault(
                        width: width*0.6,
                        title: 'Unidade',
                        list: listUnit,
                        select: selectUnit,
                        onChanged: (value){
                          setState(() {
                            selectUnit = value!;
                            validatorDropDown = true;
                            selectTeam = null;
                          });
                          getTeam();
                        },
                      ),
                      DropDownButtonDefault(
                        width: width*0.6,
                        title: 'Equipe',
                        list: listTeam,
                        select: selectTeam,
                        onChanged: (value){
                          setState(() {
                            selectTeam = value!;
                          });
                        },
                      ),
                      Container(
                        margin: EdgeInsets.symmetric(vertical: 5),
                        color: ColorPalette.white,
                        width: width*0.6,
                        height: height*0.05,
                        child: SwitchListTile(
                          title: TextDefault(text: 'Sincronizar Cidadãos Fora de Área',fontSize: 15,color: Colors.black,),
                          onChanged:(v)=>setState(()=>citizenOutArea=v),
                          value: citizenOutArea,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              loading?Container():ButtonDefault(
                onPressed: ()=>checkLogin(),
                title: 'Sincronizar',
                width: width*0.6,
              ),
              SizedBox(height: 10),
              loading?Container():Container(
                padding: EdgeInsets.symmetric(vertical: 5),
                width: width*0.6,
                child: TextDefault(
                  text: '',
                  // text: 'Cidade Sincronizada: ${widget.args!.model.nameCityFront!=''?widget.args!.model.nameCityFront:''}',
                  fontWeigth: FontWeight.bold,
                  fontSize: 18,
                  color: Colors.black,
                  textAlign: TextAlign.center,
                  maxLines: 2,
                ),
              ),
              TextDefault(text: error,color: ColorPalette.red),
            ],
          ),
        ),
      ),
    );
  }
}
