import 'package:flutter/material.dart';
import 'package:line_icons/line_icons.dart';
import 'package:rkm/controllers/main_controllers.dart';
import 'package:rkm/screens/registers_citizen/register_citizen_screen.dart';
import 'package:rkm/config/const_variable.dart';
import 'package:rkm/service/db/db_querys.dart';
import 'package:rkm/widgets/icon_button_default.dart';
import 'package:rkm/widgets/input_search_text.dart';
import '../service/db/db_sqlite_load.dart';
import '../widgets/appbar_default.dart';
import '../widgets/item_citizen.dart';

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

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  var inputSearch = TextEditingController();
  List dataCitizen = [];
  List showResults = [];

  loadCitizen()async{
    await DbSqliteLoad().intialDB().then((db)async {
      dataCitizen = await db.query('CIDADAOS ORDER BY NOME_CIDADAO');
      // print(await db.rawQuery("SELECT * FROM CIDADAOS WHERE NOME_PAI='REGINALDO OLIVEIRA'"));
    });
    searchCitizen();
    return 'complete';
  }

  searchCitizen()async{
    if(inputSearch.text.isNotEmpty){
      showResults =[];
      for (int i =0;dataCitizen.length>i;i++) {
        String NOME_CIDADAO = '${dataCitizen[i]['NOME_CIDADAO']}';
        String CNS = '${dataCitizen[i]['CNS']}'==''?'999999999999999':'${dataCitizen[i]['CNS']}';
        String NUM_PRONTUARIO = '${dataCitizen[i]['NUM_PRONTUARIO']}'==''?'null':'${dataCitizen[i]['NUM_PRONTUARIO']}';
        List splitted = '${dataCitizen[i]['DT_NASCIMENTO']}'.split('-');
        String DT_NASCIMENTO = '00/00/0000';
        if( splitted.length==3){
          DT_NASCIMENTO = '${splitted[2]}/${splitted[1]}/${splitted[0]}';
        }
        if(
            NOME_CIDADAO.contains(inputSearch.text.toUpperCase()) ||
            NUM_PRONTUARIO.contains(inputSearch.text.toUpperCase()) ||
            DT_NASCIMENTO.contains(inputSearch.text.toUpperCase()) ||
            CNS.contains(inputSearch.text.toUpperCase())
        ){
          if(showResults.length<10){
            showResults.add(dataCitizen[i]);
          }
        }
      }
      setState(() {
      });
    }else{
      setState(() {
        for(int i = 0;i<10;i++){
          showResults.add(dataCitizen[i]);
        }
      });
    }
  }

  _searchInit(){
    searchCitizen();
  }


  @override
  void initState() {
    super.initState();
    loadCitizen();
    inputSearch.addListener(_searchInit);
  }
  @override
  void dispose() {
    super.dispose();
    inputSearch.dispose();
  }

  @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 - Início'),
      body: Container(
        padding: EdgeInsets.all(10),
        width: width,
        height: height,
        decoration: ConstVariable().backgroundGradient,
        child: ListView(
          children: [
            Row(
              children: [
                InputSearchText(
                    hint: 'Busca cidadão (Por NOME ou CNS ou PRONTUÁRIO ou DATA NASCIMENTO)',
                    fontSize: 10,
                    controller: inputSearch,
                    width: width*0.72,
                ),
                IconButtonDefault(
                    icon: Icons.person_add,
                    onPressed: ()=> Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => RegisterCitizenScreen(listData: [],)),
                    )
                ),
                IconButtonDefault(
                    icon: Icons.article,
                    onPressed: ()=>Navigator.pushNamed(context, '/attendance_list')
                ),
                IconButtonDefault(
                    icon: LineIcons.edit,
                    onPressed: ()=>Navigator.pushNamed(context, '/edit_procedure')
                ),
              ],
            ),
            Container(
              width: width,
              height: height*0.8,
              child: showResults.length == 0?Container():ListView.builder(
                itemCount: showResults.length,
                itemBuilder: (context,index){

                  List splitted = '${showResults[index]['DT_NASCIMENTO']}'.split('-');
                  String date='00/00/0000';
                  if(splitted.length==3){
                    date = '${splitted[2]}/${splitted[1]}/${splitted[0]}';
                  }

                  return ItemCitizen(
                    date:  date,
                    name:  '${showResults[index]['NOME_CIDADAO']}',
                    mother:'${showResults[index]['NOME_MAE']}',
                    numberCNS: '${showResults[index]['CNS']}'=='null'||'${showResults[index]['CNS']}'==''?'999999999999999':'${showResults[index]['CNS']}',
                    numberMedicalRecord: '${showResults[index]['NUM_PRONTUARIO']}'==''?'-----':'${showResults[index]['NUM_PRONTUARIO']}',
                    onTap: ()async {
                      await DBQuerys().buscaCidadao(showResults[index]['NOME_CIDADAO']).then((list){
                        Navigator.push(
                          context,
                          MaterialPageRoute(builder:
                              (context) => RegisterCitizenScreen(listData: list,)),
                        );
                      });
                    }
                  );
                }
              )
            ),
          ],
        ),
      ),
    );
  }
}
