import 'package:diplomaticquarterapp/analytics/google-analytics.dart';
import 'package:diplomaticquarterapp/locator.dart';
import 'package:diplomaticquarterapp/theme/colors.dart';
import 'package:diplomaticquarterapp/uitl/CalendarUtils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/uitl/utils_new.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart';
import 'package:manage_calendar_events/manage_calendar_events.dart';
import 'package:permission_handler/permission_handler.dart';

Future<Map<Permission, PermissionStatus>> requestPermissions() async {
  var permissionResults = [Permission.calendar].request();
  return permissionResults;
}

showReminderDialog(BuildContext context, DateTime dateTime, String doctorName, String eventId, String appoDateFormatted, String appoTimeFormatted,
    {Function onSuccess, String title, String description, Function(int) onMultiDateSuccess}) async {
  if (await Permission.calendar.request().isGranted) {
    _showReminderDialog(context, dateTime, doctorName, eventId, appoDateFormatted, appoTimeFormatted,
        onSuccess: onSuccess, title: title, description: description, onMultiDateSuccess: onMultiDateSuccess);
  } else {
    requestPermissions().then((results) {
      if (results[Permission.calendar].isGranted) {
        _showReminderDialog(context, dateTime, doctorName, eventId, appoDateFormatted, appoTimeFormatted,
            onSuccess: onSuccess, title: title, description: description, onMultiDateSuccess: onMultiDateSuccess);
      }
    });
  }
}

final CalendarPlugin _myPlugin = CalendarPlugin();

Future<void> _showReminderDialog(BuildContext context, DateTime dateTime, String doctorName, String eventId, String appoDateFormatted, String appoTimeFormatted,
    {Function onSuccess, String title, String description, Function(int) onMultiDateSuccess}) async {
  return showDialog<void>(
    context: context,
    barrierDismissible: true, // user must tap button!
    builder: (BuildContext context) {
      return Dialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(0.0)),
        insetPadding: EdgeInsets.all(21),
        child: ReminderDialog(
          onClick: (int i) async {
            String text = "";
            if (i == 0) {
              // Before 30 mints
              dateTime = Jiffy(dateTime).subtract(minutes: 30).dateTime;
              text = "30 minutes";
              // dateTime.add(new Duration(minutes: -30));
            } else if (i == 1) {
              // Before 1 hour
              // dateTime.add(new Duration(minutes: -60));
              dateTime = Jiffy(dateTime).subtract(hours: 1).dateTime;
              text = "1 hours";
            } else if (i == 2) {
              // Before 1 hour and 30 mints
              // dateTime.add(new Duration(minutes: -90));
              dateTime = Jiffy(dateTime).subtract(hours: 1, minutes: 30).dateTime;
              text = "1 hours 30 minutes";
            } else if (i == 3) {
              // Before 2 hours
              // dateTime.add(new Duration(minutes: -120));
              dateTime = Jiffy(dateTime).subtract(hours: 2).dateTime;
              text = "2 hours";
            }

            locator<GAnalytics>().appointment.appointment_reminder_time(reminde_before: text);
            if (onMultiDateSuccess == null) {
              CalendarUtils calendarUtils = await CalendarUtils.getInstance();
              calendarUtils
                  .createOrUpdateEvent(
                      title: title ?? TranslationBase.of(context).reminderTitle + " " + doctorName,
                      description: description ?? "At " + appoDateFormatted + " " + appoTimeFormatted,
                      scheduleDateTime: dateTime,
                      eventId: eventId)
                  .then((value) {});

              onSuccess();
            } else {
              onMultiDateSuccess(i);
            }
          },
        ),
      );
    },
  );
}

class ReminderDialog extends StatefulWidget {
  Function onClick;

  ReminderDialog({this.onClick});

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

class _ReminderDialogState extends State<ReminderDialog> {
  int i = 0;

  @override
  Widget build(BuildContext context) {
    return Container(
      //width: MediaQuery.of(context).size.width / 0.8,
      padding: const EdgeInsets.all(20.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Icon(
                Icons.notifications_active,
                color: Color(0xff2B353E),
                size: 50,
              ),
              IconButton(
                icon: Icon(Icons.clear),
                color: Color(0xff2B353E),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            ],
          ),
          mHeight(20),
          Text(
            TranslationBase.of(context).appointmentReminder,
            style: TextStyle(
              fontSize: 16,
              color: Color(0xff2B353E),
              fontWeight: FontWeight.w600,
              letterSpacing: -0.48,
            ),
          ),
          mHeight(20),
          Text(
            TranslationBase.of(context).pleaseSelectFromBelowOptions,
            style: TextStyle(
              fontSize: 12,
              color: Color(0xff2B353E),
              fontWeight: FontWeight.w600,
              letterSpacing: -0.48,
            ),
          ),
          Row(
            children: [
              Radio<int>(
                value: 0,
                groupValue: i,
                onChanged: (int value) {
                  setState(() {
                    i = value;
                  });
                },
              ),
              Text(
                TranslationBase.of(context).appoReminder30,
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  letterSpacing: -0.48,
                ),
              ),
            ],
          ),
          Row(
            children: [
              Radio<int>(
                value: 1,
                groupValue: i,
                onChanged: (int value) {
                  setState(() {
                    i = value;
                  });
                },
              ),
              Text(
                TranslationBase.of(context).appoReminder60,
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  letterSpacing: -0.48,
                ),
              ),
            ],
          ),
          Row(
            children: [
              Radio<int>(
                value: 2,
                groupValue: i,
                onChanged: (int value) {
                  setState(() {
                    i = value;
                  });
                },
              ),
              Text(
                TranslationBase.of(context).appoReminder90,
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  letterSpacing: -0.48,
                ),
              ),
            ],
          ),
          Row(
            children: [
              Radio<int>(
                value: 3,
                groupValue: i,
                onChanged: (int value) {
                  setState(() {
                    i = value;
                  });
                },
              ),
              Text(
                TranslationBase.of(context).appoReminder120,
                style: TextStyle(
                  fontSize: 12,
                  fontWeight: FontWeight.w600,
                  letterSpacing: -0.48,
                ),
              ),
            ],
          ),
          mHeight(12),
          DefaultButton(
            TranslationBase.of(context).save,
            () {
              widget.onClick(i);
              Navigator.pop(context);
            },
            color: CustomColors.green,
          ),
        ],
      ),
    );
  }
}
