import 'package:flutter/material.dart';
import 'package:line_icons/line_icons.dart';
import 'package:rkm/config/color_palette.dart';
import 'package:rkm/config/const_variable.dart';
import 'package:rkm/service/db/db_querys.dart';
import 'package:rkm/service/db/db_sqlite_load.dart';
import 'package:rkm/widgets/appbar_default.dart';
import 'package:rkm/widgets/button_default.dart';
import '../../widgets/alert_dialog_default.dart';
import '../../widgets/dropdown_button_default.dart';
import '../../widgets/input_search_text.dart';
import '../../widgets/subtitle_containers.dart';
import '../../widgets/text_default.dart';
import '../../widgets/title_containers.dart';

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

  @override
  State<MainProceduresScreen> createState() => _MainProceduresScreenState();
}

class _MainProceduresScreenState extends State<MainProceduresScreen> {

  String? selectService;
  String? selectProcedure;
  String? selectCBO;
  String COD_PROC_SIGTAP = '';
  String CODIGO_CBO = '';
  bool disableButton = true;
  var controllerProceduresSearch = TextEditingController();
  var controllerCBOSearch = TextEditingController();
  List listProcedures = [];
  List listProcInit = [];
  List listCBOS = [];
  List showResultSearchProcedures = [];
  List showResultSearchCBO = [];

  @override
  void initState() {
    super.initState();
    loadProcedures();
    loadCBOS();
    loadProceduresInit();
    controllerProceduresSearch.addListener(_searchProceduresInit);
    controllerCBOSearch.addListener(_searchCBOSInit);
  }

  _searchProceduresInit(){
    searchProcedures();
  }

  _searchCBOSInit(){
    searchCBOS();
  }

  searchProcedures()async{
    showResultSearchProcedures =[];
    if(controllerProceduresSearch.text.isNotEmpty){
      for (int i =0;listProcedures.length>i;i++) {
        String procedure = '${listProcedures[i]}';

        if(procedure.contains(controllerProceduresSearch.text.toUpperCase())){
          if(showResultSearchProcedures.length<10){
            showResultSearchProcedures.add(listProcedures[i]);
          }
        }
      }
      setState(() {});
    }else{
      if(listProcedures.length>9){
        for(int i = 0;i<10;i++){
          showResultSearchProcedures.add(listProcedures[i]);
        }
      }else{
        for(int i = 0;i<listProcedures.length;i++){
          showResultSearchProcedures.add(listProcedures[i]);
        }
      }
      setState(() {});
    }
  }
  searchCBOS()async{
    showResultSearchCBO =[];
    if(controllerCBOSearch.text.isNotEmpty){
      for (int i =0;listCBOS.length>i;i++) {
        String cbo = '${listCBOS[i]}';

        if(cbo.contains(controllerCBOSearch.text)){
          if(showResultSearchCBO.length<10){
            showResultSearchCBO.add(listCBOS[i]);
          }
        }
      }
      setState(() {});
    }else{
      if(listCBOS.length>9){
        for(int i = 0;i<10;i++){
          showResultSearchCBO.add(listCBOS[i]);
        }
      }else{
        for(int i = 0;i<listCBOS.length;i++){
          showResultSearchCBO.add(listCBOS[i]);
        }
      }
      setState(() {});
    }
  }

  loadProcedures()async{
    // [{COD_PROC_SIGTAP: 0101010010,
    // DESC_PROC_SIGTAP: ATIVIDADE EDUCATIVA / ORIENTAÇÃO EM GRUPO NA ATENÇÃO PRIMÁRIA,
    // GRUPO_PROC_SIGTAP: 01, QTDE_MAXIMA: 9999, IDADE_MIN: 833, IDADE_MAX: 833, SEXO: N}]
    List list = await DBQuerys().buscaprocedimento();
    if(list.length != 0){
      for(int i = 0; list.length > i;i++){
        listProcedures.add('${list[i]['COD_PROC_SIGTAP']} - ${list[i]['DESC_PROC_SIGTAP']}');
      }
      setState(() {});
    }
  }

  loadCBOS()async{
    // [{CODIGO_CBO: 223208, DESCRICAO_CBO: Cirurgião dentista - clínico geral}]
    List list = await DBQuerys().buscaCBOS();
    if(list.length != 0){
      for(int i = 0; list.length > i;i++){
        listCBOS.add('${list[i]['CODIGO_CBO']} - ${list[i]['DESCRICAO_CBO']}');
      }
      // print(listCBOS);
      setState(() {});
    }
  }

  loadProceduresInit()async{
    listProcInit = [];
    // [{CODIGO_CBO: 223208, DESCRICAO_CBO: Cirurgião dentista - clínico geral}]
    listProcInit = await DBQuerys().buscaProcIniciais();
    // print(listProcInit);
    setState(() {});
  }

  saveProcedures()async{
    List splittedCODProc = selectProcedure!.split(' ');
    List splittedCODCBO = selectCBO!.split(' ');
    List check = await DBQuerys().buscaProceduresCBO(splittedCODProc[0], splittedCODCBO[0]);
    if(check.length!=0){
      Map<String, dynamic> row = {
        'ATENDIMENTO'     : selectService=='ATENDIMENTO INDIVIDUAL'?1:2,
        'COD_PROC_SIGTAP' : splittedCODProc[0],
        'CODIGO_CBO'      : splittedCODCBO[0],
      };
      await DbSqliteLoad().saveProceduresInit(row).then((value){
        loadProceduresInit();
      });
    }else{
      AlertDialogDefault().alert(context, 'Aviso', 'Procedimento não permitido para o CBO informado!', 'OK');
    }
  }
  deleteProcedures(int ATENDIMENTO,String CODIGO_CBO,String COD_PROC_SIGTAP)async{
    // [{ATENDIMENTO: 1, COD_PROC_SIGTAP: 0101010010, CODIGO_CBO: 223208}, {ATENDIMENTO: 2, COD_PROC_SIGTAP: 0101010010, CODIGO_CBO: 223208}]
    await DbSqliteLoad().deleteProceduresInit(ATENDIMENTO,CODIGO_CBO,COD_PROC_SIGTAP).then((value){
      loadProceduresInit();
    });
  }

  updateContext(){
    Navigator.pop(context);
    if(selectProcedure!= null && selectCBO!= null && selectService!=null){
      disableButton = false;
    }
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {

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

    return Scaffold(
      appBar: AppBarDefault().appbar(context, 'RKM AB - Procedimentos Iniciais'),
      body: Container(
        padding: EdgeInsets.all(10),
        decoration: ConstVariable().backgroundGradient,
        child: ListView(
          children: [
            Card(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TitleContainers(title: 'Adicionar Procedimento Inicial',),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      SubtitleContainers(title: 'Atendimento',width: width*0.5),
                      Spacer(),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 10),
                        child: DropDownButtonDefault(
                          widthContainer: width*0.35,
                          title: '',
                          width: width*0.4,
                          list: ['ATENDIMENTO INDIVIDUAL','VISITA DOMICILIAR'],
                          select: selectService,
                          onChanged: (value){
                            setState(() {
                              selectService = value!;
                              if(selectProcedure!= null && selectCBO!= null && selectService!=null){
                                disableButton = false;
                              }
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                  Divider(color: ColorPalette.black54,endIndent: 10,indent: 10,height: 1),
                  GestureDetector(
                      onTap: (){
                        controllerProceduresSearch.text = '';
                        searchProcedures();
                        showDialog(
                          context: context,
                          builder: (context){
                            return AlertDialog(
                              scrollable: true,
                              content: StatefulBuilder(
                                  builder: (context, setState) {
                                    //aqui
                                    return Column(
                                      children: [
                                        InputSearchText(
                                          onChanged: (v){
                                            setState((){
                                              searchProcedures();
                                            });
                                          },
                                          controller: controllerProceduresSearch,
                                          width: width*0.8,
                                          hint: 'Buscar...',
                                          color: ColorPalette.titleContainer,
                                          border: false,
                                        ),
                                        Container(
                                          padding: EdgeInsets.symmetric(vertical: 10),
                                          width:  width*0.8,
                                          child:  Container(
                                            width: width*0.8,
                                            height: height*0.6,
                                            padding: EdgeInsets.symmetric(horizontal: 10),
                                            child: ListView.separated(
                                                separatorBuilder:(context,index)=> Divider(color: ColorPalette.black54,height: 5,),
                                                itemCount: showResultSearchProcedures.length,
                                                itemBuilder: (context,index){
                                                  return Container(
                                                    width: width*0.8,
                                                    color: ColorPalette.white,
                                                    child: ListTile(
                                                      onTap: (){
                                                        selectProcedure =  showResultSearchProcedures[index];
                                                        updateContext();
                                                      },
                                                      title: TextDefault(
                                                        color: ColorPalette.black54,
                                                        text:  showResultSearchProcedures[index],
                                                        fontSize: 16,
                                                        maxLines: 2,
                                                      ),
                                                    ),
                                                  );
                                                }
                                            ),
                                          ),
                                        ),
                                      ],
                                    );
                                  }),
                            );
                          },
                        );
                      },
                    child: selectProcedure!=null?
                    Container(
                      width: width,
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          SubtitleContainers(title: 'Procedimento',width: width*0.3,),
                          Spacer(),
                          Container(
                            padding: EdgeInsets.symmetric(horizontal: 5),
                            width: width*0.65,
                            child: TextDefault(
                              color: ColorPalette.black54,
                              text: selectProcedure!,
                              fontSize: 15,
                            ),
                          )
                        ],
                      ),
                    ):
                    SubtitleContainers(title: 'Procedimento')
                  ),
                  GestureDetector(
                      onTap: (){
                        controllerCBOSearch.text = '';
                        searchCBOS();
                        showDialog(
                          context: context,
                          builder: (context){
                            return AlertDialog(
                              scrollable: true,
                              content: StatefulBuilder(
                                  builder: (context, setState) {
                                    //aqui
                                    return Column(
                                      children: [
                                        InputSearchText(
                                          onChanged: (v){
                                            setState((){
                                              searchCBOS();
                                            });
                                          },
                                          controller: controllerCBOSearch,
                                          width: width*0.8,
                                          hint: 'Buscar...',
                                          color: ColorPalette.titleContainer,
                                          border: false,
                                        ),
                                        Container(
                                          padding: EdgeInsets.symmetric(vertical: 10),
                                          width:  width*0.8,
                                          child:  Container(
                                            width: width*0.8,
                                            height: height*0.6,
                                            padding: EdgeInsets.symmetric(horizontal: 10),
                                            child: ListView.separated(
                                                separatorBuilder:(context,index)=> Divider(color: ColorPalette.black54,height: 5,),
                                                itemCount: showResultSearchCBO.length,
                                                itemBuilder: (context,index){
                                                  return Container(
                                                    width: width*0.8,
                                                    color: ColorPalette.white,
                                                    child: ListTile(
                                                      onTap: (){
                                                        selectCBO =  showResultSearchCBO[index];
                                                        updateContext();
                                                      },
                                                      title: TextDefault(
                                                        color: ColorPalette.black54,
                                                        text:  showResultSearchCBO[index],
                                                        fontSize: 16,
                                                        maxLines: 2,
                                                      ),
                                                    ),
                                                  );
                                                }
                                            ),
                                          ),
                                        ),
                                      ],
                                    );
                                  }),
                            );
                          },
                        );
                      },
                      child: selectCBO!=null?
                      Container(
                        width: width,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            SubtitleContainers(title: 'CBO',width: width*0.3,),
                            Spacer(),
                            Container(
                              padding: EdgeInsets.symmetric(horizontal: 5),
                              width: width*0.65,
                              child: TextDefault(
                                color: ColorPalette.black54,
                                text: selectCBO!,
                                fontSize: 15,
                              ),
                            )
                          ],
                        ),
                      ):
                      SubtitleContainers(title: 'CBO')
                  ),
                  Padding(
                    padding: const EdgeInsets.all(10),
                    child: ButtonDefault(
                      title: 'Adicionar',
                      borderColor: disableButton?ColorPalette.buttonDisable:ColorPalette.appBar,
                      background: ColorPalette.appBar,
                      disableColor: ColorPalette.buttonDisable,
                      textColor: ColorPalette.white,
                      onPressed: disableButton?null:(){
                        if(selectProcedure!= null && selectCBO!= null && selectService!=null){
                          saveProcedures();
                        }
                      },
                      width: double.infinity,
                    ),
                  )
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 10.0,horizontal: 2),
              child: Card(
                child: Column(
                  children: [
                    TitleContainers(
                      title: 'Procedimentos',
                    ),
                    Container(
                      height: height*listProcInit.length*0.08,
                      child: ListView.builder(
                        itemCount: listProcInit.length,
                        itemBuilder: (context,index){
                          return Padding(
                            padding: const EdgeInsets.all(10.0),
                            child: Row(
                              children: [
                                TextDefault(
                                    text: '${listProcInit[index]['ATENDIMENTO']==1?'ATENDIMENTO INDIVIDUAL':'VISITA DOMICILIAR'} - ${listProcInit[index]['COD_PROC_SIGTAP']} - ${listProcInit[index]['CODIGO_CBO']}',
                                    fontSize: 15,
                                    color: ColorPalette.black54,
                                ),
                                Spacer(),
                                IconButton(
                                  icon: Icon(LineIcons.trash),
                                  onPressed: (){
                                    deleteProcedures(listProcInit[index]['ATENDIMENTO'],listProcInit[index]['CODIGO_CBO'],listProcInit[index]['COD_PROC_SIGTAP']);
                                  },
                                )
                              ],
                            ),
                          );
                        },
                      ),
                    )
                  ],
                )
              ),
            ),
          ],
        ),
      ),
    );
  }
}
