import 'package:flutter/material.dart';
import 'package:rkm/config/color_palette.dart';
import 'package:rkm/config/const_variable.dart';
import 'package:rkm/screens/registers_citizen/register_citizen_screen.dart';
import 'package:rkm/screens/select_service/atendimento_domiciliar_tela.dart';
import 'package:rkm/screens/select_service/visita_domiciliar_tela.dart';
import 'package:rkm/widgets/text_default.dart';
import 'package:sqflite/sqflite.dart';
import '../service/db/db_querys.dart';
import '../service/db/db_sqlite_load.dart';
import '../widgets/appbar_default.dart';
import '../widgets/button_default.dart';

class AttendanceListScreen extends StatefulWidget {
  String username;

  AttendanceListScreen({required this.username});

  @override
  State<AttendanceListScreen> createState() => _AttendanceListScreenState();
}

class _AttendanceListScreenState extends State<AttendanceListScreen> {

  List atendimentoDomiciliarLista = [];
  List visitaDomiciliarLista = [];
  List cadastroCidadaoLista = [];
  List cadastrosIndividuais = [];

  getData()async{
    Database db = await DbSqliteLoad().intialDB();
    // visitHome = await db.query('VISITAS_DOMICILIARES');
    visitaDomiciliarLista =await db.rawQuery('''
  SELECT VD.*, C.*
  FROM VISITAS_DOMICILIARES VD
  INNER JOIN CIDADAOS C ON VD.ID_CIDADAO = C.ID_CIDADAO
''');
    cadastroCidadaoLista = await db.query('CIDADAOS WHERE SINCRONIZADO = "N"');
    cadastrosIndividuais = await db.query('CADASTROS_INDIVIDUAIS WHERE SINCRONIZADO = "N"');
    atendimentoDomiciliarLista =await db.rawQuery('''
  SELECT AD.*, C.*
  FROM ATENDIMENTOS_DOMICILIARES AD
  INNER JOIN CIDADAOS C ON AD.ID_CIDADAO = C.ID_CIDADAO
''');
    setState(() {});
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBarDefault().appbar(context, 'RKM AB - Lista Atendimentos',widget.username),
      body: Container(
        decoration: ConstVariable().backgroundGradient,
        width: double.infinity,
        height: double.infinity,
        child: ListView(
          children: [
            Container(
              padding: ConstVariable().marginHightInput,
              color: ColorPalette.white,
              child: Column(
                children: [
                  TextDefault(
                    text: 'Atendimentos Domiciliares: ${atendimentoDomiciliarLista.length} | Visitas Domiciliares: ${visitaDomiciliarLista.length}',
                    fontWeigth: FontWeight.bold,
                    color: ColorPalette.black54,
                    fontSize: 18,
                  ),
                  TextDefault(
                    text: 'Cadastros Cidadãos Realizados / Atualizados : ${cadastroCidadaoLista.length + cadastrosIndividuais.length}',
                    fontWeigth: FontWeight.bold,
                    color: ColorPalette.black54,
                    fontSize: 18,
                  ),
                ],
              )
            ),
            Container(
              height: atendimentoDomiciliarLista.length*80,
              child: ListView.builder(
                itemCount: atendimentoDomiciliarLista.length,
                itemBuilder: (context,i){

                  List dataList = atendimentoDomiciliarLista[i]['DATA'].toString().split('-');
                  String data = '${dataList[2]}/${dataList[1]}/${dataList[0]}';

                  return Card(
                    color: Colors.white,
                    child: Row(
                      children: [
                        Container(
                          height: 70,
                          width: 50,
                          decoration: BoxDecoration(
                              color: Color(0XFF666666),
                              borderRadius: BorderRadius.only(bottomLeft: Radius.circular(10),topLeft: Radius.circular(10))
                          ),
                          alignment: Alignment.center,
                          child: TextDefault(text: 'A.D.',color: Colors.white,fontSize: 22,fontWeigth: FontWeight.bold,),
                        ),
                        SizedBox(width: 10,),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            TextDefault(text:atendimentoDomiciliarLista[i]['NOME_CIDADAO'].toString(),color: ColorPalette.black54,fontWeigth: FontWeight.w700,),
                            Row(
                              children: [
                                TextDefault(text:'DATA ATENDIMENTO: $data',color: ColorPalette.black54,fontWeigth: FontWeight.w700,),
                                SizedBox(width: 20,),
                                TextDefault(text:'SINCRONIZADO : ${atendimentoDomiciliarLista[i]['SINCRONIZADO']}',color: ColorPalette.black54,fontWeigth: FontWeight.w700,),
                              ],
                            ),
                          ],
                        ),
                        Spacer(),
                        atendimentoDomiciliarLista[i]['SINCRONIZADO']!='S'?IconButton(
                          icon: Container(
                            padding: EdgeInsets.all(8.0),
                            decoration: BoxDecoration(
                              color: Color(0XFF990000),
                              borderRadius: BorderRadius.circular(50),
                            ),
                            child: Icon(Icons.delete, color: Colors.white, size: 40,),
                          ),
                          onPressed: ()async{
                            await showDialog(
                            context: context,
                            builder: (context){
                              return AlertDialog(
                                title: TextDefault(text: 'Aviso',color: ColorPalette.black54,textAlign: TextAlign.center,),
                                content: TextDefault(text: 'Deseja apagar esse "Atendimento Domiciliar" ?',color: ColorPalette.black54,),
                                actions: [
                                  ButtonDefault(
                                    onPressed: ()async{
                                      Database db = await DbSqliteLoad().intialDB();
                                      await db.delete(
                                        'ATENDS_DOM_COMPL',
                                        where: 'ID_ATENDIMENTO_DOMICILIAR = ?',
                                        whereArgs: [atendimentoDomiciliarLista[i]['ID_ATENDIMENTO_DOMICILIAR']],
                                      );
                                      await db.delete(
                                        'ATENDS_DOM_PROC',
                                        where: 'ID_ATENDIMENTO_DOMICILIAR = ?',
                                        whereArgs: [atendimentoDomiciliarLista[i]['ID_ATENDIMENTO_DOMICILIAR']],
                                      );
                                      await db.delete(
                                        'ATENDIMENTOS_DOMICILIARES',
                                        where: 'ID_ATENDIMENTO_DOMICILIAR = ?',
                                        whereArgs: [atendimentoDomiciliarLista[i]['ID_ATENDIMENTO_DOMICILIAR']],
                                      );
                                      Navigator.of(context).pop();
                                      getData();
                                    },
                                    title: 'Sim',
                                    background: ColorPalette.appBar,
                                    borderColor: ColorPalette.appBar,
                                    textColor: ColorPalette.white,
                                  ),
                                  ButtonDefault(
                                    onPressed: ()=>Navigator.of(context).pop(false),
                                    title: 'Não',
                                    background: ColorPalette.white,
                                    borderColor: ColorPalette.white,
                                    textColor: ColorPalette.black54,
                                  ),
                                ],
                              );
                            }
                            );
                          },
                        ):Container(),
                        atendimentoDomiciliarLista[i]['SINCRONIZADO']!='S'?IconButton(
                          icon: Container(
                            padding: EdgeInsets.all(8.0),
                            decoration: BoxDecoration(
                              color: Colors.orangeAccent,
                              borderRadius: BorderRadius.circular(50),
                            ),
                            child: Icon(Icons.edit, color: Colors.white, size: 40,),
                          ),
                          onPressed: (){
                            Navigator.push(
                              context,
                              MaterialPageRoute(builder:(context) => AtendimentoDomiciliarTela(name: atendimentoDomiciliarLista[i]['NOME_CIDADAO'],username: widget.username,dados: atendimentoDomiciliarLista[i],)),
                            );
                          },
                        ):Container(),
                      ],
                    ));
                },
              ),
            ),
            Container(
              height: visitaDomiciliarLista.length*80,
              child: ListView.builder(
                itemCount: visitaDomiciliarLista.length,
                itemBuilder: (context,i){

                  //print(visitHome[i]);
                  List dataList = visitaDomiciliarLista[i]['DT_ATENDIMENTO'].toString().split('-');
                  String data = '${dataList[2]}/${dataList[1]}/${dataList[0]}';

                  return Card(
                    color: Colors.white,
                    child: Row(
                      children: [
                        Container(
                          height: 70,
                          width: 50,
                          decoration: BoxDecoration(
                            color: Color(0XFF006633),
                            borderRadius: BorderRadius.only(bottomLeft: Radius.circular(10),topLeft: Radius.circular(10))
                          ),
                          alignment: Alignment.center,
                          child: TextDefault(text: 'V.D.',color: Colors.white,fontSize: 22,fontWeigth: FontWeight.bold,),
                        ),
                        SizedBox(width: 10,),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            TextDefault(text:visitaDomiciliarLista[i]['NOME_CIDADAO'].toString(),color: ColorPalette.black54,fontWeigth: FontWeight.w700,),
                            Row(
                              children: [
                                TextDefault(text:'DATA ATENDIMENTO: $data',color: ColorPalette.black54,fontWeigth: FontWeight.w700,),
                                SizedBox(width: 20,),
                                TextDefault(text:'SINCRONIZADO : ${visitaDomiciliarLista[i]['SINCRONIZADO']}',color: ColorPalette.black54,fontWeigth: FontWeight.w700,),
                              ],
                            ),
                          ],
                        ),
                        Spacer(),
                        visitaDomiciliarLista[i]['SINCRONIZADO']!='S'?IconButton(
                          icon: Container(
                            padding: EdgeInsets.all(8.0),
                            decoration: BoxDecoration(
                              color: Color(0XFF990000),
                              borderRadius: BorderRadius.circular(50),
                            ),
                            child: Icon(Icons.delete, color: Colors.white, size: 40,),
                          ),
                          onPressed: ()async{
                            await showDialog(
                                context: context,
                                builder: (context){
                                  return AlertDialog(
                                    title: TextDefault(text: 'Aviso',color: ColorPalette.black54,textAlign: TextAlign.center,),
                                    content: TextDefault(text: 'Deseja apagar essa "Visita Domiciliar" ?',color: ColorPalette.black54,),
                                    actions: [
                                      ButtonDefault(
                                        onPressed: ()async{
                                          Database db = await DbSqliteLoad().intialDB();
                                          await db.delete(
                                            'VISITAS_DOMICILIARES_COMPL',
                                            where: 'ID_VISITA_DOMICILIAR = ?',
                                            whereArgs: [visitaDomiciliarLista[i]['ID_VISITA_DOMICILIAR']],
                                          );
                                          await db.delete(
                                            'VISITAS_DOMICILIARES',
                                            where: 'ID_VISITA_DOMICILIAR = ?',
                                            whereArgs: [visitaDomiciliarLista[i]['ID_VISITA_DOMICILIAR']],
                                          );
                                          Navigator.of(context).pop();
                                          getData();
                                        },
                                        title: 'Sim',
                                        background: ColorPalette.appBar,
                                        borderColor: ColorPalette.appBar,
                                        textColor: ColorPalette.white,
                                      ),
                                      ButtonDefault(
                                        onPressed: ()=>Navigator.of(context).pop(false),
                                        title: 'Não',
                                        background: ColorPalette.white,
                                        borderColor: ColorPalette.white,
                                        textColor: ColorPalette.black54,
                                      ),
                                    ],
                                  );
                                }
                            );
                          },
                        ):Container(),
                        visitaDomiciliarLista[i]['SINCRONIZADO']!='S'?IconButton(
                          icon: Container(
                            padding: EdgeInsets.all(8.0),
                            decoration: BoxDecoration(
                              color: Colors.orangeAccent,
                              borderRadius: BorderRadius.circular(50),
                            ),
                            child: Icon(Icons.edit, color: Colors.white, size: 40,),
                          ),
                          onPressed: (){
                            Navigator.push(
                              context,
                              MaterialPageRoute(builder:(context) => VisitaDomiciliarTela(name: visitaDomiciliarLista[i]['NOME_CIDADAO'],username: widget.username,dados: visitaDomiciliarLista[i],)),
                            );
                          },
                        ):Container(),
                      ],
                    ));
                },
              ),
            ),
            Container(
              height: cadastroCidadaoLista.length*80,
              child: ListView.builder(
                itemCount: cadastroCidadaoLista.length,
                itemBuilder: (context,i){

                  List dataList1 = cadastroCidadaoLista[i]['DT_HORA_CADASTRO'].toString().split(' ');
                  List dataList2 = dataList1[0].split('-');
                  String data = '${dataList2[2]}/${dataList2[1]}/${dataList2[0]}';

                  return Card(
                      color: Colors.white,
                      child: Row(
                        children: [
                          Container(
                            height: 70,
                            width: 50,
                            decoration: BoxDecoration(
                                color: Color(0XFF990000),
                                borderRadius: BorderRadius.only(bottomLeft: Radius.circular(10),topLeft: Radius.circular(10))
                            ),
                            alignment: Alignment.center,
                            child: TextDefault(text: 'C',color: Colors.white,fontSize: 22,fontWeigth: FontWeight.bold,),
                          ),
                          SizedBox(width: 10,),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              TextDefault(text:cadastroCidadaoLista[i]['NOME_CIDADAO'].toString(),color: ColorPalette.black54,fontWeigth: FontWeight.w700,),
                              Row(
                                children: [
                                  TextDefault(text:'DATA CADASTRO : $data',color: ColorPalette.black54,fontWeigth: FontWeight.w700,),
                                  SizedBox(width: 20,),
                                  TextDefault(text:'SINCRONIZADO : ${cadastroCidadaoLista[i]['SINCRONIZADO']}',color: ColorPalette.black54,fontWeigth: FontWeight.w700,),
                                ],
                              ),
                            ],
                          ),
                          Spacer(),
                          cadastroCidadaoLista[i]['ORIGEM']=='C' && cadastroCidadaoLista[i]['SINCRONIZADO']=='N'
                              ?IconButton(
                                icon: Container(
                                  padding: EdgeInsets.all(8.0),
                                  decoration: BoxDecoration(
                                    color: Color(0XFF990000),
                                    borderRadius: BorderRadius.circular(50),
                                  ),
                                  child: Icon(Icons.delete, color: Colors.white, size: 40,),
                                ),
                                onPressed: ()async{
                                  await showDialog(
                                      context: context,
                                      builder: (context){
                                        return AlertDialog(
                                          title: TextDefault(text: 'Aviso',color: ColorPalette.black54,textAlign: TextAlign.center,),
                                          content: TextDefault(text: 'Deseja apagar esse cidadão?',color: ColorPalette.black54,),
                                          actions: [
                                            ButtonDefault(
                                              onPressed: ()async{
                                                Database db = await DbSqliteLoad().intialDB();
                                                await db.delete(
                                                  'CIDADAOS', // Substitua pelo nome da sua tabela
                                                  where: 'ID_CIDADAO = ?',
                                                  whereArgs: [cadastroCidadaoLista[i]['ID_CIDADAO']],
                                                );
                                                Navigator.of(context).pop();
                                                getData();
                                              },
                                              title: 'Sim',
                                              background: ColorPalette.appBar,
                                              borderColor: ColorPalette.appBar,
                                              textColor: ColorPalette.white,
                                            ),
                                            ButtonDefault(
                                              onPressed: ()=>Navigator.of(context).pop(false),
                                              title: 'Não',
                                              background: ColorPalette.white,
                                              borderColor: ColorPalette.white,
                                              textColor: ColorPalette.black54,
                                            ),
                                          ],
                                        );
                                      }
                                  );
                                },
                              )
                              :Container(),
                            cadastroCidadaoLista[i]['SINCRONIZADO']=='N'?IconButton(
                            icon: Container(
                              padding: EdgeInsets.all(8.0),
                              decoration: BoxDecoration(
                                color: Colors.orangeAccent,
                                borderRadius: BorderRadius.circular(50),
                              ),
                              child: Icon(Icons.edit, color: Colors.white, size: 40,),
                            ),
                            onPressed: ()async {
                              await DBQuerys().buscaCidadao(cadastroCidadaoLista[i]['NOME_CIDADAO']).then((list){
                                // print(showResults[index]['CD_USUARIO_SUS']);
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(builder:(context) => RegisterCitizenScreen(listData: list,username: widget.username,)),
                                );
                              });
                            },
                          ):Container(),
                        ],
                      ));
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
