import 'package:device_calendar/device_calendar.dart';
import 'package:diplomaticquarterapp/core/viewModels/medical/ActiveMedicationsViewModel.dart';
import 'package:diplomaticquarterapp/core/viewModels/project_view_model.dart';
import 'package:diplomaticquarterapp/pages/base/base_view.dart';
import 'package:diplomaticquarterapp/uitl/CalendarUtils.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/buttons/secondary_button.dart';
import 'package:diplomaticquarterapp/widgets/data_display/text.dart';
import 'package:diplomaticquarterapp/widgets/others/app_scaffold_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:provider/provider.dart';

import 'DayCheckBoxDialog.dart';

// ignore: must_be_immutable
class ReminderPage extends StatefulWidget {
  final int frequency;
  final int days;
  final String itemDescription;

  List<DateTime> _scheduleList = List();
  List<DayOfWeek> daysOfWeek = [
    DayOfWeek.Monday,
    DayOfWeek.Tuesday,
    DayOfWeek.Wednesday,
    DayOfWeek.Thursday,
    DayOfWeek.Friday,
    DayOfWeek.Saturday,
    DayOfWeek.Sunday
  ];

  DateTime startDay;
  DateTime endDay;

  ReminderPage({Key key, this.frequency, this.days, this.itemDescription}) {
    startDay = DateTime.now();
    endDay = DateTime.now().add(Duration(days: days));
    int hour = (24 ~/ frequency).round();
    int durations = 24 ~/ hour;
    for (int count = 0; count < durations; count++) {
      _scheduleList.add(DateTime(DateTime.now().year, DateTime.now().month,
          DateTime.now().day, (hour * count)));
    }
  }

  @override
  _ReminderPageState createState() => _ReminderPageState();
}

class _ReminderPageState extends State<ReminderPage> {
  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);

    return BaseView<ActiveMedicationsViewModel>(
      builder: (_, model, w) => AppScaffold(
        baseViewModel: model,
        isShowAppBar: true,
        appBarTitle: TranslationBase.of(context).reminder,
        body: SingleChildScrollView(
          child: Container(
            margin: EdgeInsets.all(8.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: double.maxFinite,
                  child: Texts(TranslationBase.of(context).reminderDes),
                ),
                Divider(),
                SizedBox(
                  height: 12,
                ),
                Texts(TranslationBase.of(context).startDay),
                SizedBox(
                  height: 6,
                ),
                InkWell(
                  onTap: () {
                    DatePicker.showDatePicker(context,
                        showTitleActions: true,
                        minTime: DateTime(
                            DateTime.now().year, DateTime.now().month - 1, 1),
                        maxTime: DateTime.now(), onConfirm: (date) {
                      setState(() {
                        widget.startDay = date;
                      });
                    },
                        currentTime: widget.startDay,
                        locale: projectViewModel.localeType);
                  },
                  child: Container(
                    padding: EdgeInsets.all(12),
                    width: double.infinity,
                    height: 65,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        color: Colors.white),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Texts(getStartDay()),
                        Icon(
                          Icons.calendar_today,
                          color: Colors.black,
                        )
                      ],
                    ),
                  ),
                ),
                SizedBox(
                  height: 12,
                ),
                Texts(TranslationBase.of(context).endDay),
                SizedBox(
                  height: 6,
                ),
                InkWell(
                  onTap: () {
                    DatePicker.showDatePicker(context,
                        showTitleActions: true,
                        minTime: DateTime(
                            DateTime.now().year, DateTime.now().month - 1, 1),
                        maxTime: DateTime.now(), onConfirm: (date) {
                      setState(() {
                        widget.endDay = date;
                      });
                    },
                        currentTime: widget.endDay,
                        locale: projectViewModel.localeType);
                  },
                  child: Container(
                    padding: EdgeInsets.all(12),
                    width: double.infinity,
                    height: 65,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        color: Colors.white),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Texts(getEndDay()),
                        Icon(
                          Icons.calendar_today,
                          color: Colors.black,
                        )
                      ],
                    ),
                  ),
                ),
                SizedBox(
                  height: 12,
                ),
                Texts(TranslationBase.of(context).days),
                SizedBox(
                  height: 6,
                ),
                InkWell(
                  onTap: () => confirmSelectDayDialog(),
                  child: Container(
                    padding: EdgeInsets.all(12),
                    width: double.infinity,
                    height: 65,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(12),
                        color: Colors.white),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                            child: Texts(
                          getDays(),
                        )),
                        Icon(
                          Icons.arrow_drop_down,
                          color: Colors.black,
                        )
                      ],
                    ),
                  ),
                ),
                ...List.generate(
                    widget._scheduleList.length,
                    (index) => Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            SizedBox(
                              height: 7,
                            ),
                            Texts(TranslationBase.of(context).scheduleTime),
                            SizedBox(
                              height: 7,
                            ),
                            InkWell(
                              onTap: () {
                                DatePicker.showTimePicker(context,
                                    showTitleActions: true, onConfirm: (date) {
                                  setState(() {
                                    widget._scheduleList[index] = date;
                                  });
                                },
                                    currentTime: widget._scheduleList[index],
                                    locale: projectViewModel.localeType);
                              },
                              child: Container(
                                padding: EdgeInsets.all(12),
                                width: double.infinity,
                                height: 65,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(12),
                                    color: Colors.white),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceBetween,
                                  children: [
                                    Texts(getDateTime(
                                        widget._scheduleList[index])),
                                    Icon(
                                      Icons.access_time,
                                      color: Colors.black,
                                    )
                                  ],
                                ),
                              ),
                            ),
                          ],
                        )),
                Container(
                  width: double.maxFinite,
                  height: MediaQuery.of(context).size.height * 0.12,
                ),
              ],
            ),
          ),
        ),
        bottomSheet: Container(
          width: double.infinity,
          height: MediaQuery.of(context).size.height * 0.2,
          padding: EdgeInsets.all(10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SecondaryButton(
                label: TranslationBase.of(context).ok,
                color: Colors.grey[800],
                textColor: Colors.white,
                onTap: () {
                  schedule();
                },
              ),
              SizedBox(
                height: 15,
              ),
              SecondaryButton(
                label: TranslationBase.of(context).cancel,
                color: Colors.red[800],
                textColor: Colors.white,
                onTap: () {
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  schedule() async {
    List<DateTime> scheduleDateTime =
        calculateDaysInterval(widget.startDay, widget.endDay);

    CalendarUtils calendarUtils = await CalendarUtils.getInstance();

    calendarUtils.createOrUpdateEvents(
        scheduleList: widget._scheduleList,
        description: widget.itemDescription,
        title: widget.itemDescription,
        scheduleDateTime: scheduleDateTime);

    Navigator.pop(context);
  }

  List<DateTime> calculateDaysInterval(DateTime startDate, DateTime endDate) {
    List<DateTime> days = [];
    for (int i = 0; i <= endDate.difference(startDate).inDays; i++) {
      widget._scheduleList.forEach((element) {
        days.add(startDate.add(
            Duration(days: i, hours: element.hour, minutes: element.minute)));
      });
    }
    return days;
  }

  String getStartDay() {
    return "${DateUtil.getMonth(widget.startDay.month)} ${widget.startDay.day}, ${widget.startDay.year}";
  }

  String getEndDay() {
    return "${DateUtil.getMonth(widget.endDay.month)} ${widget.endDay.day}, ${widget.endDay.year}";
  }

  String getDateTime(DateTime dateTime) {
    return '${dateTime.hour}:${dateTime.minute}';
  }

  String getDays() {
    String days = "";
    widget.daysOfWeek.forEach((element) {
      days += "${DateUtil.getDay(element)},";
    });
    return days;
  }

  void confirmSelectDayDialog() {
    showDialog(
      context: context,
      child: DayCheckBoxDialog(
        title: 'Select Day',
        selectedDaysOfWeek: widget.daysOfWeek,
        onValueSelected: (value) {
          setState(() {
            widget.daysOfWeek = value;
          });
        },
      ),
    );
  }
}
