import 'package:flutter/material.dart';
import 'package:school_management_system/api/calender_requests.dart';
import 'package:school_management_system/components/default_values.dart';
import 'package:school_management_system/screens/welcome/welcome_screen.dart';
import 'package:syncfusion_flutter_calendar/calendar.dart';

late Future<Calendar> _studentData;
late Future<Calendar> _schoolData;
late Future<bool> _checkToken;

class SchoolCalender extends StatefulWidget {
  const SchoolCalender({super.key});

  @override
  State<SchoolCalender> createState() => _SchoolCalenderState();
}

class _SchoolCalenderState extends State<SchoolCalender> {
  List<Calenderrdetail> calendar = [];

  @override
  void initState() {
    _checkToken = checkTokenValidity();
    super.initState();
    _studentData = getStudentCalender(loginId, session, semester);
    _schoolData = getSchoolCalender('HOLIDAY', session, semester);
  }

  @override
  Widget build(BuildContext context) {
 
     _checkToken.then(
      (value) {;
        if (!value) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) {
                return const WelcomeScreen();
              },
            ),
          );
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('Session Time Out / Sign Back In'),
            ),
          );
        }
      },
    );

    return FutureBuilder<List<Calendar>>(
        future: Future.wait([_schoolData, _studentData]),
        builder: (context, snapshot) {
          List<Widget> children;
          if (snapshot.hasData) {
            calendar = [];
            var levelOne = 0;
            while (levelOne < snapshot.data!.length) {
              var levelTwo = 0;
              while (levelTwo <
                  snapshot.data![levelOne].calenderrdetails!.length) {
                calendar
                    .add(snapshot.data![levelOne].calenderrdetails![levelTwo]);
                levelTwo++;
              }
              levelOne++;
            }
            children = [
              const SizedBox(height: 20),
              Expanded(
                child: SfCalendar(
                  view: CalendarView.month,
                  showDatePickerButton: true,
                  showTodayButton: true,
                  dataSource: MeetingDataSource(_getDataSource()),
                  monthViewSettings: const MonthViewSettings(
                      showAgenda: true,
                      appointmentDisplayMode:
                          MonthAppointmentDisplayMode.appointment),
                ),
              ),
            ];
          } else if (snapshot.hasError) {
            calendar = [];
            children = [
              const Icon(
                Icons.error_outline,
                color: Colors.red,
                size: 60,
              ),
              Padding(
                padding: const EdgeInsets.only(top: 16),
                child: Text('Error: ${snapshot.error}'),
              ),
            ];
          } else {
            calendar = [];
            children = const [
              SizedBox(
                width: 60,
                height: 60,
                child: CircularProgressIndicator(),
              ),
              Padding(
                padding: EdgeInsets.only(top: 16),
                child: Text('Loading Data...'),
              ),
            ];
          }

          return Container(
            padding: const EdgeInsets.all(20),
            color: Colors.white,
            child: Column(
              children: children,
            ),
          );
        });
  }

  List<Meeting> _getDataSource() {
    List<Meeting> meetings = <Meeting>[];

    var calendarCount = 0;
    if (calendar.isNotEmpty) {
      while (calendarCount < calendar.length) {
        bool? allday = calendar[calendarCount].allday;

        DateTime? sdate = calendar[calendarCount].startdate;
        String? stime = calendar[calendarCount].starttime;

        DateTime? starttime = DateTime(
            sdate!.year,
            sdate.month,
            sdate.day,
            int.parse(stime!.split(':')[0]),
            int.parse(stime.split(':')[1]),
            int.parse(stime.split(':')[2]));

        DateTime? edate = calendar[calendarCount].enddate;
        String? etime = calendar[calendarCount].endtime;

        DateTime? endtime = DateTime(
            edate!.year,
            edate.month,
            edate.day,
            int.parse(etime!.split(':')[0]),
            int.parse(etime.split(':')[1]),
            int.parse(etime.split(':')[2]));

        // DateTime? enddate = calendar[initVal].enddate;
        String? event = calendar[calendarCount].event;
//        String? recurrenceRule = calendar[initVal].occurence;

        meetings.add(Meeting(
            event!, starttime, endtime, primaryColor, allday!, ""));
        calendarCount++;
      }
    }

    // // final DateTime today = DateTime.now();
    // final DateTime startTime = DateTime(2024, 03, 16, 9, 0, 0);
    // // DateTime(today.year, today.month, today.day, 9, 0, 0);
    // final DateTime endTime = startTime.add(const Duration(hours: 2));

    // meetings.add(Meeting(
    //     'Birthday', startTime, endTime, const Color(0xFF0F8644), false));
    return meetings;
  }
}

class MeetingDataSource extends CalendarDataSource {
  MeetingDataSource(this.source);

  List<Meeting> source;

  @override
  List<dynamic> get appointments => source;

  @override
  DateTime getStartTime(int index) {
    return source[index].from;
  }

  @override
  DateTime getEndTime(int index) {
    return source[index].to;
  }

  @override
  String getSubject(int index) {
    return source[index].eventName;
  }

  @override
  Color getColor(int index) {
    return source[index].background;
  }

  @override
  bool isAllDay(int index) {
    return source[index].isAllDay;
  }

  @override
  String getRecurrenceRule(int index) {
    return appointments[index].recurrenceRule;
  }
}

class Meeting {
  Meeting(this.eventName, this.from, this.to, this.background, this.isAllDay,
      this.recurrenceRule);

  String eventName;
  DateTime from;
  DateTime to;
  Color background;
  bool isAllDay;
  String recurrenceRule;
}
