import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:rkm_educa_app/componentes/item_evento_home.dart';
import 'package:rkm_educa_app/controllers/main_controllers.dart';
import 'package:rkm_educa_app/modelos/estudante_modelo.dart';
import 'package:rkm_educa_app/telas/tela_avisos.dart';
import 'package:rkm_educa_app/utils/cores.dart';
import 'package:rkm_educa_app/componentes/text_custom.dart';
import 'package:rkm_educa_app/utils/dimensoes.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import '../componentes/drawer_custom.dart';
import '../modelos/evento_modelo.dart';

class TelaSituacaoEscolar extends StatefulWidget {
  EstudanteModelo estudanteModelo;

  TelaSituacaoEscolar({
      required this.estudanteModelo
  });

  @override
  State<TelaSituacaoEscolar> createState() => _TelaSituacaoEscolarState();
}

class _TelaSituacaoEscolarState extends State<TelaSituacaoEscolar> {

  late List<_ChartData> data;
  late TooltipBehavior _tooltip;
  List <EventoModelo>eventos = [];
  List <EventoModelo>ocorrencias = [];
  bool carregandoEventos = true;
  bool carregandoOcorrencias = true;

  buscarEventos()async{
    final url = '${widget.estudanteModelo.URL}/calendario_home?'
        'HOJE=${DateTime.now().year}-${DateTime.now().month}-${DateTime.now().day}&'
        'COD_ESCOLA=${widget.estudanteModelo.dados[widget.estudanteModelo.nroAluno]['CD_CAD_DIVERSO']}&'
        'CIDADE=${widget.estudanteModelo.cidade}';
    // print(url);
    final response = await http.get(Uri.parse(url));
    var map = json.decode(response.body);
    // print(map);
    List list = map;
    for(int i=0; list.length>i;i++){
      List data = list[i]['DT_CALENDARIO'].toString().split('-');
      eventos.add(EventoModelo(titulo: list[i]['NO_EVENTO'], data: '${data[2]}/${data[1]}/${data[0]}'));
    }
    carregandoEventos = false;
    setState(() {});
  }

  buscarOcorrencia()async{
    final url = '${widget.estudanteModelo.URL}/ocorrencia?'
        'MATRICULA=${widget.estudanteModelo.dados[widget.estudanteModelo.nroAluno]['CD_MATRICULA']}&'
        'CIDADE=${widget.estudanteModelo.cidade}';
    print(url);
    final response = await http.get(Uri.parse(url));
    var map = json.decode(response.body);
    if(map==false){
      ocorrencias.add(EventoModelo(titulo: 'Nenhuma ocorrência', data: ''));
    }else{
      ocorrencias.add(EventoModelo(titulo: map['DESC_OCORRENCIA'], data: map['DATA']));
    }
    carregandoOcorrencias = false;
    setState(() {});
  }
  @override
  void initState() {
    super.initState();
    MainControllers().salvarLog(widget.estudanteModelo, 'DASHBOARD');
    buscarEventos();
    buscarOcorrencia();
    // data = [
    //   _ChartData('Faltas', 10,Color(0xffD9D9D9)),
    //   _ChartData('Presenças', 90,Color(0xff43A65F)),
    // ];
    // _tooltip = TooltipBehavior(enable: true);
  }
  
  Widget graph(BuildContext context) {
    return SfCircularChart(
        tooltipBehavior: _tooltip,
        series: <CircularSeries<dynamic, dynamic>>[
          DoughnutSeries<_ChartData, String>(
              dataSource: data,
              xValueMapper: (_ChartData data, _) => data.x,
              yValueMapper: (_ChartData data, _) => data.y,
              pointColorMapper: (_ChartData data, _) => data.color,
              radius:'45'
          )
        ]
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: PaletaCores.fundoTela,
      appBar: AppBar(
        iconTheme: IconThemeData(color: PaletaCores.cinza),
        backgroundColor: Colors.transparent,
        elevation: 0,
        actions: [
          Padding(
            padding: const EdgeInsets.all(4.0),
            child: IconButton(
              onPressed: ()=>Navigator.push(context, MaterialPageRoute(builder: (context)=>TelaAvisos(estudanteModelo: widget.estudanteModelo,))),
              icon: Icon(Icons.notifications_outlined,size: 32),
            )
          )
        ],
      ),
      drawer: DrawerCustom(estudanteModelo: widget.estudanteModelo),
      body: ListView(
        children: [
          Center(
              child: TextCustom(text: 'Situção Escolar',fontWeight: FontWeight.bold,size: 20.0,),
          ),
          SizedBox(
            height: Dimensoes.height*0.1,
          ),
          Card(
            margin: EdgeInsets.symmetric(horizontal: 30),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  TextCustom(text: 'Próximos Eventos',fontWeight: FontWeight.bold,),
                  carregandoEventos?Container(
                    padding: EdgeInsets.all(50),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        CircularProgressIndicator(color: PaletaCores.cinzaClaro),
                        SizedBox(width: 20,),
                        TextCustom(text: 'Carregando Eventos')
                      ],
                    ),
                  ):Container(
                    height: eventos.length*23,
                    child: ListView.builder(
                      physics: NeverScrollableScrollPhysics(),
                      itemCount: eventos.length,
                      itemBuilder: (context,index){
                        return ItemEventoHome(titulo: eventos[index].titulo,data: eventos[index].data,);
                      }
                    ),
                  )
                ],
              ),
            ),
          ),
          SizedBox(
            height: Dimensoes.height*0.03,
          ),
          Card(
            margin: EdgeInsets.symmetric(horizontal: 30),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  TextCustom(text: 'Última Ocorrência',fontWeight: FontWeight.bold,),
                  carregandoEventos?Container(
                    padding: EdgeInsets.all(50),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        CircularProgressIndicator(color: PaletaCores.cinzaClaro),
                        SizedBox(width: 20,),
                        TextCustom(text: 'Carregando Ocorrência')
                      ],
                    ),
                  ):Row(
                    children: [
                      Container(
                          width: Dimensoes.width*0.5,
                          child: TextCustom(text:ocorrencias.length==0?'': ocorrencias[0].titulo,)
                      ),
                      Container(
                          alignment: Alignment.center,
                          width: Dimensoes.width*0.3,
                          child: TextCustom(text:ocorrencias.length==0?'': ocorrencias[0].data,)
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _ChartData {
  _ChartData(this.x, this.y, this.color);

  final String x;
  final double y;
  final Color color;
}
