import 'dart:io';

import 'package:hmg_patient_app/analytics/google-analytics.dart';
import 'package:hmg_patient_app/config/config.dart';
import 'package:hmg_patient_app/locator.dart';
import 'package:hmg_patient_app/services/permission/permission_service.dart';
import 'package:hmg_patient_app/theme/colors.dart';
import 'package:hmg_patient_app/uitl/CalendarUtils.dart';
import 'package:hmg_patient_app/uitl/date_uitl.dart';
import 'package:hmg_patient_app/uitl/gif_loader_dialog_utils.dart';
import 'package:hmg_patient_app/uitl/translations_delegate_base.dart';
import 'package:hmg_patient_app/uitl/utils.dart';
import 'package:hmg_patient_app/uitl/utils_new.dart';
import 'package:hmg_patient_app/widgets/buttons/defaultButton.dart';
import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart';
import 'package:permission_handler/permission_handler.dart';

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

showReminderDialog(BuildContext context, DateTime dateTime, String doctorName, String eventId, String appoDateFormatted, String appoTimeFormatted,
    {required Function() onSuccess, String? title, String? description, Function(int)? onMultiDateSuccess, bool isMultiAllowed = false}) async {
  if (Platform.isAndroid) {
    if (await PermissionService.isCalendarPermissionEnabled()) {
      _showReminderDialog(context, dateTime, doctorName, eventId, appoDateFormatted, appoTimeFormatted,
          onSuccess: onSuccess, title: title, description: description, onMultiDateSuccess: onMultiDateSuccess, isMultiAllowed: isMultiAllowed);
    } else {
      Utils.showPermissionConsentDialog(context, TranslationBase.of(context).calendarPermission, () async {
        if (await Permission.calendarFullAccess.request().isGranted) {
          _showReminderDialog(context, dateTime, doctorName, eventId, appoDateFormatted, appoTimeFormatted,
              onSuccess: onSuccess, title: title, description: description, onMultiDateSuccess: onMultiDateSuccess, isMultiAllowed: isMultiAllowed);
        }
      });
    }
  } else {
    if (await Permission.calendarWriteOnly.request().isGranted) {
      if (await Permission.calendarFullAccess.request().isGranted) {
        _showReminderDialog(context, dateTime, doctorName, eventId, appoDateFormatted, appoTimeFormatted,
            onSuccess: onSuccess, title: title, description: description, onMultiDateSuccess: onMultiDateSuccess, isMultiAllowed: isMultiAllowed);
      }
    }
  }
}

Future<void> _showReminderDialog(BuildContext providedContext, DateTime dateTime, String doctorName, String eventId, String appoDateFormatted, String appoTimeFormatted,
    {required Function onSuccess, String? title, String? description, Function(int)? onMultiDateSuccess, bool? isMultiAllowed}) async {
  return showDialog<void>(
    context: providedContext,
    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.parseFromDateTime(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.parseFromDateTime(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.parseFromDateTime(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.parseFromDateTime(dateTime).subtract(hours: 2).dateTime;
              text = "2 hours";
            }
            if (!isMultiAllowed!) {
              if (onMultiDateSuccess == null) {
                CalendarUtils calendarUtils = await CalendarUtils.getInstance();
                await calendarUtils.createOrUpdateEvent(
                    title: title ?? TranslationBase.of(providedContext).reminderTitle + " " + doctorName,
                    description: description ?? "At " + appoDateFormatted + " " + appoTimeFormatted,
                    scheduleDateTime: dateTime,
                    eventId: eventId);
                onSuccess();
              }
            } else {
              onMultiDateSuccess!(i);
            }
            locator<GAnalytics>().appointment.appointment_reminder_time(reminde_before: text);
          },
        ),
      );
    },
  );
}

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,
          ),
        ],
      ),
    );
  }
}
