import 'package:flutter/material.dart';
import 'package:rkm/screens/home_screen.dart';
import 'package:rkm/service/db/db_sqlite_Sigtap.dart';
import '../../config/color_palette.dart';
import '../../service/api/api_data_import_sigtap.dart';
import '../../service/db/db_sqlite_load.dart';
import '../../widgets/button_default.dart';
import '../../widgets/text_default.dart';

class ImportSigtapScreen extends StatefulWidget {
  const ImportSigtapScreen({Key? key}) : super(key: key);

  @override
  State<ImportSigtapScreen> createState() => _ImportSigtapScreenState();
}

class _ImportSigtapScreenState extends State<ImportSigtapScreen> {

  String mode ='';
  String urlAPI ='';
  String nameCityApi ='';
  String stage = 'Conectando ...';
  bool finish = false;

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

  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'];
    }).then((value){
      setState(() {});
      importSigtap();
    });
  }

  importSigtap()async{
    await DbSqliteSigtap().deleteSigtap().then((value)async{
      setState(() {
        stage = "Etapa 1 de 4 - Importando informações do CONECTASUS";
      });
      await ApiDataImportSigtap().loadSIGTAP(urlAPI, mode, nameCityApi).then((valueAPI)async{
        setState(() {
          stage = "Etapa 2 de 4 - Gravando os Procedimentos no Aplicativo";
        });
        // print(value['procedimentos']);
        await DbSqliteSigtap().saveProceduresSigtapDB(valueAPI['procedimentos']).then((value)async{
          await DbSqliteSigtap().saveProceduresRegisterSigtapDB(valueAPI['procedimentosRegistros']).then((value)async{
            setState(() {
              stage = "Etapa 3 de 4 - Gravando os CIDs no Aplicativo";
            });
            await DbSqliteSigtap().saveSigtapCID(valueAPI['CID']).then((value)async{
              await DbSqliteSigtap().saveProceduresSigtapCID(valueAPI['procedimentosCID']).then((value)async{
                setState(() {
                  stage = "Etapa 4 de 4 - Gravando os CIDs no Aplicativo";
                });
                await DbSqliteSigtap().saveCBOSigtap(valueAPI['CBO']).then((value)async{
                  await DbSqliteSigtap().saveProceduresCBOSigtap(valueAPI['procedimentosCBO']).then((value)async{
                    await DbSqliteSigtap().saveSyncSigtap(valueAPI['competencia']).then((value)async{
                      setState(() {
                        finish = true;
                      });
                    });
                  });
                });
              });
            });
          });
        });
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    double height = MediaQuery.of(context).size.height;

    return Scaffold(
      bottomSheet: Container(
        color: ColorPalette.appBar,
        width: double.infinity,
        padding: EdgeInsets.all(15),
        child: finish
            ?Row(
          children: [
            Spacer(),
            ButtonDefault(
              onPressed: (){
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(builder: (context) => HomeScreen()),
                );
              },
              title: 'Continuar',
              width: width*0.3,
              height: height*0.05,
              textColor: ColorPalette.white,
              background: ColorPalette.appBar,
              borderColor: ColorPalette.appBar,
            ),
          ],
        ):TextDefault(
          text: stage,
          color: ColorPalette.white,
          fontSize: 15,
          fontWeigth: FontWeight.bold,
        ),
      ),
      body: Container(
        padding: EdgeInsets.only(top: 100),
        decoration: BoxDecoration(
            color: ColorPalette.grayBackground,
            image: DecorationImage(
              fit: BoxFit.fitHeight,
              image: AssetImage('assets/images/load_image.png'),
            )
        ),
        width: double.infinity,
        height: double.infinity,
        child: finish?ListView(
          children: [
            Image.asset('assets/images/logo.PNG',width: width*0.25,height: height*0.1,),
            Image.asset('assets/images/sigtap-done.png',width: width*0.9,height: height*0.2,),
          ],
        ):Column(
          children: [
            Image.asset('assets/images/logo.PNG',width: width*0.5,),
            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(),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 50.0),
              child: Image.asset('assets/images/loading.gif',width: width*0.2,height: height*0.1,),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 5.0,horizontal: 5),
              child: TextDefault(
                text: 'Aguarde enquanto a Importação SIGTAP é realizada.\n\n'
                      'Esse processo pode levar vários minutos dependendo da sua conexão!',
                maxLines: 5,
                textAlign: TextAlign.center,
                color: ColorPalette.black54,
                fontSize: 18,
                fontWeigth: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
