import 'dart:convert';

import 'package:diplomaticquarterapp/models/Appointments/FreeSlot.dart';
import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';

import '../../../uitl/date_uitl.dart';

class DocAvailableAppointments extends StatefulWidget {
  @override
  _DocAvailableAppointmentsState createState() =>
      _DocAvailableAppointmentsState();
}

class _DocAvailableAppointmentsState extends State<DocAvailableAppointments>
    with TickerProviderStateMixin {
  Map<DateTime, List> _events;
  AnimationController _animationController;
  CalendarController _calendarController;

  var selectedDate = "";
  var jsonFreeSlots;

  List docFreeSlots = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    final _selectedDay = DateTime.now();

    this.selectedDate = DateUtil.getMonthDayYearDateFormatted(DateTime.now());

    _events = {
      _selectedDay: ['Event A0']
    };

    _getJSONSlots().then((value) => {
          setState(() => {_events.clear(), _events = value})
        });

//    _selectedEvents = _events[_selectedDay] ?? [];
    _calendarController = CalendarController();

    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 400),
    );

    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    _calendarController.dispose();
    super.dispose();
  }

  void _onDaySelected(DateTime day, List events) {
    print('CALLBACK: _onDaySelected');
    setState(() {
//      _selectedEvents = events;
      this.selectedDate =  DateUtil.getMonthDayYearDateFormatted(day);
    });
  }

  void _onVisibleDaysChanged(
      DateTime first, DateTime last, CalendarFormat format) {
    print('CALLBACK: _onVisibleDaysChanged');
  }

  void _onCalendarCreated(
      DateTime first, DateTime last, CalendarFormat format) {
    print('CALLBACK: _onCalendarCreated');
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(20.0)
        ),
        margin: EdgeInsets.all(20.0),
        padding: EdgeInsets.only(bottom: 10.0, top: 10.0),
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            Text(selectedDate,
                style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold)),
            _buildTableCalendarWithBuilders(),
          ],
        ),
      ),
    );
  }

  Future<Map<DateTime, List>> _getJSONSlots() async {
    Map<DateTime, List> _eventsParsed;
    List<FreeSlot> slotsList = [];
    String data = await DefaultAssetBundle.of(context)
        .loadString("assets/json/freeSlots.json");
    jsonFreeSlots = json.decode(data.toString());
    for (var i = 0; i < 4000; i++) {
      slotsList.add(FreeSlot(
          DateUtil.convertStringToDate(jsonFreeSlots['FreeTimeSlots'][i]),
          ['slot']));
    }
    _eventsParsed =
        Map.fromIterable(slotsList, key: (e) => e.slot, value: (e) => e.event);
    return _eventsParsed;
  }

  Widget _buildTableCalendarWithBuilders() {
    return TableCalendar(
      locale: 'en_US',
      calendarController: _calendarController,
      events: _events,
//      holidays: _holidays,
      initialCalendarFormat: CalendarFormat.month,
      startDay: DateTime.now(),
      formatAnimation: FormatAnimation.slide,
      startingDayOfWeek: StartingDayOfWeek.sunday,
      weekendDays: [DateTime.friday, DateTime.saturday],
      availableGestures: AvailableGestures.horizontalSwipe,
      availableCalendarFormats: const {
        CalendarFormat.month: '',
        CalendarFormat.week: '',
      },
      calendarStyle: CalendarStyle(
        outsideDaysVisible: false,
        weekendStyle: TextStyle().copyWith(color: Colors.blue[800]),
        holidayStyle: TextStyle().copyWith(color: Colors.blue[800]),
      ),
      daysOfWeekStyle: DaysOfWeekStyle(
        weekendStyle: TextStyle().copyWith(color: Colors.blue[600]),
      ),
      headerStyle: HeaderStyle(
        centerHeaderTitle: true,
        formatButtonVisible: false,
      ),
      builders: CalendarBuilders(
        selectedDayBuilder: (context, date, _) {
          return FadeTransition(
            opacity: Tween(begin: 0.0, end: 1.0).animate(_animationController),
            child: Container(
              margin: const EdgeInsets.all(4.0),
              padding: const EdgeInsets.only(top: 5.0, left: 6.0),
              color: Colors.transparent,
              width: 0,
              height: 0,
              child: Text(
                '${date.day}',
                style: TextStyle().copyWith(fontSize: 16.0),
              ),
            ),
          );
        },
        todayDayBuilder: (context, date, _) {
          return Container(
            margin: const EdgeInsets.all(4.0),
            padding: const EdgeInsets.only(top: 5.0, left: 6.0),
            color: Colors.amber[400],
            width: 0,
            height: 0,
            child: Text(
              '${date.day}',
              style: TextStyle().copyWith(fontSize: 16.0),
            ),
          );
        },
        markersBuilder: (context, date, events, holidays) {
          final children = <Widget>[];

          if (events.isNotEmpty) {
            children.add(
              Positioned(
                right: 4,
                bottom: 4,
                child: _buildEventsMarker(date, events),
              ),
            );
          }

          return children;
        },
      ),
      onDaySelected: (date, events) {
        _onDaySelected(date, events);
        _animationController.forward(from: 0.0);
      },
      onVisibleDaysChanged: _onVisibleDaysChanged,
      onCalendarCreated: _onCalendarCreated,
    );
  }

  Widget _buildEventsMarker(DateTime date, List events) {
    return Container(
//      duration: const Duration(milliseconds: 10),
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: _calendarController.isSelected(date)
            ? Colors.green[400]
            : _calendarController.isToday(date)
                ? Colors.brown[300]
                : Colors.blue[400],
      ),
      width: 40.0,
      height: 40.0,
      child: Center(
        child: Text(
          '${date.day}',
          style: TextStyle().copyWith(
            color: Colors.white,
            fontSize: 14.0,
          ),
        ),
      ),
    );
  }
}
