import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_calendar_carousel/classes/event.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/componentes/item_agenda.dart';
import 'package:rkm_educa_app/componentes/text_custom.dart';
import 'package:rkm_educa_app/modelos/estudante_modelo.dart';
import 'package:rkm_educa_app/modelos/evento_modelo.dart';
import 'package:rkm_educa_app/utils/cores.dart';
import 'package:rkm_educa_app/utils/dimensoes.dart';
import 'package:http/http.dart' as http;
import '../controllers/main_controllers.dart';

class TelaAgenda extends StatefulWidget {
  EstudanteModelo estudanteModelo;

  TelaAgenda({
    required this.estudanteModelo
});

  @override
  State<TelaAgenda> createState() => _TelaAgendaState();
}

class _TelaAgendaState extends State<TelaAgenda> {

  List<EventoModelo> listDatas = [];
  bool carregandoEventos = true;
  DateTime _currentDate = DateTime.now();
  DateTime dataAtual = DateTime.now();
  EventList<Event> _markedDateMap = new EventList<Event>(
    events: {},
  );

  Widget _eventIcon(String dia,Color cor) => Container(
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(30),
      color: cor,
    ),
    width: 40,
    height: 40,
    child: Center(
      child: TextCustom(text: dia,fontWeight: FontWeight.bold,size: 14.0,color: cor==Color(0xffee1d24)?Colors.white:PaletaCores.cinza),
    ),
  );

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

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

  buscarEventos()async{
    // int quantidadeDias = DateTime(dataAtual.year, dataAtual.month, 0).day;
    // print(quantidadeDias);
    _markedDateMap.clear();
    listDatas.clear();
    carregandoEventos = true;
    setState(() {});

    final url = '${widget.estudanteModelo.URL}/calendario?'
        'MES=${dataAtual.year}-${dataAtual.month}-01&'
        'COD_ESCOLA=${widget.estudanteModelo.dados[widget.estudanteModelo.nroAluno]['CD_CAD_DIVERSO']}&'
        'QUANTIDADE=31&'
        'CIDADE=${widget.estudanteModelo.cidade}';
    print(url);
    final response = await http.get(Uri.parse(url));
    var map = json.decode(response.body);
    // print(map);
    if(map!=false){
      List list = map;
      List titulo = [];
      List<EventoModelo> listD = [];
      for(int i = 0; list.length>i;i++){
        List data = list[i]['DT_CALENDARIO'].toString().split('-');
        titulo.add(list[i]['NO_EVENTO'].toString().trim());

        listD.add(EventoModelo(
            titulo: list[i]['NO_EVENTO'].toString().trim(),
            data: '${data[2]}/${data[1]}/${data[0]}',
            cor: int.parse(list[i]['NO_COR'].toString().trim()=='#0ff'?'0xffe1e1a1':'0xff'+list[i]['NO_COR'].toString().replaceAll("#", ''))));

        _markedDateMap.add(
            DateTime(int.parse(data[0]),int.parse(data[1]),int.parse(data[2])),
            Event(
                date: DateTime(int.parse(data[0]),int.parse(data[1]),int.parse(data[2])),
                icon: _eventIcon(data[2],list[i]['NO_COR'].toString().trim()=='#0ff'?Color(0xffe1e1a1)
                    :Color(int.parse('0xff'+list[i]['NO_COR'].toString().replaceAll("#", '')))
                )
            )
        );
      }
      List limpando = titulo.toSet().toList();

      for(int i = 0; limpando.length>i;i++){
        int index = 0;
        index = titulo.indexOf(limpando[i]);
        listDatas.add(listD[index]);
      }
    }
    carregandoEventos = false;
    setState(() {});
  }

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

  @override
  Widget build(BuildContext context) {

    final _calendario = CalendarCarousel<Event>(
      locale: 'pt',
      weekdayTextStyle: TextStyle(color: PaletaCores.cinza,fontSize: 14,fontFamily: 'Nunito',),
      disableDayPressed: true,
      daysTextStyle: textStyle,
      selectedDayButtonColor: Colors.red,
      weekendTextStyle: textStyleFDS,
      markedDatesMap: _markedDateMap,
      height: Dimensoes.height*0.45,
      targetDateTime: dataAtual,
      markedDateCustomTextStyle: textStyle,
      markedDateMoreShowTotal: null,
      showHeader: false,
      todayTextStyle: textStyle,
      isScrollable: false,
      todayButtonColor: PaletaCores.verdeCalendario,
      selectedDayTextStyle: textStyle,
      minSelectedDate: _currentDate.subtract(Duration(days: 360)),
      maxSelectedDate: _currentDate.add(Duration(days: 360)),
      markedDateIconBuilder: (event){
        return event.icon;
      },
    );

    return Scaffold(
      appBar: AppBarCustom().appbar(context, 'AGENDA ESCOLAR'),
      drawer: DrawerCustom(estudanteModelo: widget.estudanteModelo),
      body:  carregandoEventos?Center(
        child: Container(
          padding: EdgeInsets.all(80),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(color: PaletaCores.cinzaClaro),
              SizedBox(width: 20,),
              TextCustom(text: 'Carregando Eventos')
            ],
          ),
        ),
      ):ListView(
        padding: EdgeInsets.all(10),
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              IconButton(
                  onPressed: () {
                    setState(() {
                      dataAtual = DateTime(dataAtual.year, dataAtual.month -1);
                      buscarEventos();
                    });
                  },
                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);
                      buscarEventos();
                    });
                  },
                  icon: Icon(Icons.arrow_right,size: 30,color: PaletaCores.cinzaClaro,)
              ),
            ],
          ),
          _calendario,
          Container(
            width: Dimensoes.width*0.8,
            height: 30,
            padding: const EdgeInsets.symmetric(horizontal: 5.0),
            child:  Padding(
              padding: EdgeInsets.symmetric(vertical: 0),
              child:   TextCustom(text: 'LEGENDA',size: 14.0,fontWeight: FontWeight.bold),
            ),
          ),
          Container(width: double.infinity,height: 2,color: PaletaCores.divider,),
           Container(
              padding: EdgeInsets.symmetric(vertical: 0),
              height: Dimensoes.height*0.38,
              child: ListView.builder(
                itemCount: listDatas.length,
                itemBuilder: (context,index){
                  return ItemAgenda(cor: listDatas[index].cor, titulo: listDatas[index].titulo);
                },
              ),
            )
        ],
      ),
    );
  }
}
