import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_calendar_carousel/classes/event.dart';
import 'package:flutter_calendar_carousel/classes/event_list.dart';
import 'package:flutter_calendar_carousel/flutter_calendar_carousel.dart';
import 'package:intl/intl.dart';
import 'package:rkm_educa_app/componentes/appbar_custom.dart';
import 'package:rkm_educa_app/componentes/drawer_custom.dart';
import 'package:rkm_educa_app/modelos/estudante_modelo.dart';
import 'package:http/http.dart' as http;
import '../componentes/text_custom.dart';
import '../controllers/main_controllers.dart';
import '../utils/cores.dart';
import '../utils/dimensoes.dart';

class TelaChamada extends StatefulWidget {
  EstudanteModelo estudanteModelo;

  TelaChamada({
    required this.estudanteModelo
});

  @override
  State<TelaChamada> createState() => _TelaChamadaState();
}

class _TelaChamadaState extends State<TelaChamada> {

  List presenca = [];
  bool carregando = false;
  DateTime _currentDate = DateTime.now();
  DateTime dataAtual = DateTime.now();
  EventList<Event> _markedDateMap = new EventList<Event>(
    events: {},
  );

  TextStyle textStyle = TextStyle(
      color: PaletaCores.cinzaClaro,
      fontWeight: FontWeight.bold,
      fontFamily: 'Nunito',
      fontSize: 14
  );

  TextStyle textStyleToday = TextStyle(
      color: PaletaCores.branco,
      fontWeight: FontWeight.bold,
      fontFamily: 'Nunito',
      fontSize: 14
  );

  TextStyle textStyleFDS = TextStyle(
      color: Colors.red,
      fontWeight: FontWeight.bold,
      fontFamily: 'Nunito',
      fontSize: 14
  );

  getChamada(String data)async{
    int cd = widget.estudanteModelo.dados[widget.estudanteModelo.nroAluno]['CD_MATRICULA'];
    print(widget.estudanteModelo.nroAluno);
    setState(()=>carregando=true);
    presenca.clear();
    final url = 'http://192.168.18.2:8000/presenca?CD_MATRICULA=${cd}&DATA=$data&CIDADE=${widget.estudanteModelo.cidade}';
    print(url);
    final response = await http.get(Uri.parse(url));
    var map = json.decode(response.body);
    presenca = map;
    print(presenca);
    setState(()=>carregando=false);
  }

  @override
  void initState() {
    super.initState();
    MainControllers().salvarLog(widget.estudanteModelo, 'CHAMADA');
  }

  @override
  Widget build(BuildContext context) {

    final _calendario = CalendarCarousel<Event>(
      onDayLongPressed: (DateTime date){
        setState(() {
          _currentDate = date;
        });
        print('long');
      },
      onDayPressed: (date, events) {
        setState(() => _currentDate = date);
        events.forEach((event) => print(event.title));
        List split = _currentDate.toString().split(' ');
        print(split[0]);
        getChamada(split[0]);
      },
      selectedDateTime: _currentDate,
      locale: 'pt',
      weekdayTextStyle: TextStyle(color: PaletaCores.cinza,fontSize: 14,fontFamily: 'Nunito',),
      daysTextStyle: textStyle,
      selectedDayButtonColor: Colors.green,
      weekendTextStyle: textStyleFDS,
      markedDatesMap: _markedDateMap,
      markedDateMoreShowTotal: null,
      showHeader: false,
      targetDateTime: dataAtual,
      height: Dimensoes.height*0.38,
      markedDateCustomTextStyle: textStyle,
      todayTextStyle: textStyle,
      todayButtonColor: PaletaCores.branco,
      selectedDayTextStyle: textStyleToday,
      minSelectedDate: _currentDate.subtract(Duration(days: 360)),
      maxSelectedDate: _currentDate.add(Duration(days: 360)),
      markedDateIconBuilder: (event){
        return event.icon;
      },
    );

    return Scaffold(
      appBar: AppBarCustom().appbar(context, 'CHAMADAS / PRESENÇAS'),
      drawer: DrawerCustom(estudanteModelo: widget.estudanteModelo),
      body: carregando?Center(
        child: Container(
          padding: EdgeInsets.all(80),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(color: PaletaCores.cinzaClaro),
              SizedBox(width: 20,),
              TextCustom(text: 'Carregando Informações ...')
            ],
          ),
        ),
      ):Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              IconButton(
                  onPressed: () {
                    setState(() {
                      dataAtual = DateTime(dataAtual.year, dataAtual.month -1);
                    });
                  },
                  icon: Icon(Icons.arrow_left,size: 30,color: PaletaCores.cinzaClaro,)
              ),
              TextCustom(text: DateFormat('MMMM / yyyy','pt_Br').format(dataAtual),fontWeight: FontWeight.bold),
              IconButton(
                  onPressed: () {
                    setState(() {
                      dataAtual = DateTime(dataAtual.year, dataAtual.month +1);
                    });
                  },
                  icon: Icon(Icons.arrow_right,size: 30,color: PaletaCores.cinzaClaro,)
              ),
            ],
          ),
          _calendario,
          Container(
            padding: EdgeInsets.only(bottom: 15),
            width: Dimensoes.width,
            child: TextCustom(
              textAlign: TextAlign.center,
              size: 14.0,
              fontWeight: FontWeight.bold,
              text: 'SELECIONE A DATA DESEJADA',
            ),
          ),
      presenca.length==0?  Container():Container(
            width: Dimensoes.width,
            padding: EdgeInsets.symmetric(horizontal: 10),
            child: Row(
              children: [
                Container(
                  width: Dimensoes.width*0.65,
                  child: TextCustom(
                    size: 14.0,
                    text: 'DISCIPLINAS',
                  ),
                ),
                Spacer(),
                Container(
                  width: Dimensoes.width*0.2,
                  child: TextCustom(
                    textAlign: TextAlign.center,
                    size: 14.0,
                    text: 'STATUS',
                  ),
                ),
              ],
            ),
          ),
          Container(
            height: Dimensoes.height*0.3,
            child: presenca.length==0?  Container(
              alignment: Alignment.center,
              width: Dimensoes.width,
              child: TextCustom(
                textAlign: TextAlign.center,
                size: 14.0,
                fontWeight: FontWeight.bold,
                text: 'SEM INFORMAÇÕES NESSA DATA',
              ),
            ):ListView.builder(
              itemCount: presenca.length,
              itemBuilder: (context,index){
                return Container(
                  width: Dimensoes.width,
                  padding: EdgeInsets.symmetric(horizontal: 10),
                  child: Row(
                    children: [
                      Container(
                        width: Dimensoes.width*0.65,
                        child: TextCustom(
                          size: 14.0,
                          text: presenca[index]['DESCRICAO']??'',
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Spacer(),
                      Container(
                        color: presenca[index]['FL_PRESENTE_AUSENTE']=='P'?Colors.green:Colors.red,
                        width: Dimensoes.width*0.2,
                        child: TextCustom(
                          textAlign: TextAlign.center,
                          color: Colors.white,
                          size: 14.0,
                          text: presenca[index]['FL_PRESENTE_AUSENTE']=='P'?'PRESENTE':'AUSENTE',
                        ),
                      ),
                    ],
                  ),
                );
              }
            ),
          )
        ],
      ),
    );
  }
}
