import 'dart:collection';
import 'dart:io';

import 'package:device_calendar/device_calendar.dart';
import 'package:hmg_patient_app/core/model/prescriptions/Prescriptions.dart';
import 'package:hmg_patient_app/core/model/prescriptions/prescription_report.dart';
import 'package:hmg_patient_app/core/viewModels/project_view_model.dart';
import 'package:hmg_patient_app/extensions/string_extensions.dart';
import 'package:hmg_patient_app/models/header_model.dart';
import 'package:hmg_patient_app/pages/BookAppointment/widgets/reminder_dialog.dart';
import 'package:hmg_patient_app/pages/medical/prescriptions/pharmacy_for_prescriptions_page.dart';
import 'package:hmg_patient_app/uitl/CalendarUtils.dart';
import 'package:hmg_patient_app/uitl/app_toast.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/location_util.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:hmg_patient_app/widgets/new_design/doctor_header.dart';
import 'package:hmg_patient_app/widgets/others/app_scaffold_widget.dart';
import 'package:hmg_patient_app/widgets/show_zoom_image_dialog.dart';
import 'package:hmg_patient_app/widgets/transitions/fade_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart';
import 'package:manage_calendar_events/manage_calendar_events.dart' as ios;
import 'package:provider/provider.dart';

class PrescriptionDetailsPage extends StatefulWidget {
  final PrescriptionReport? prescriptionReport;
  final Prescriptions? prescriptions;

  PrescriptionDetailsPage({Key? key, this.prescriptionReport, this.prescriptions});

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

class _PrescriptionDetailsPageState extends State<PrescriptionDetailsPage> {
  bool hasReminder = false;
  late LocationUtils locationUtils;

  @override
  void initState() {
    checkAndRemove(delete: false);
    locationUtils = new LocationUtils(isShowConfirmDialog: true, context: context);
    WidgetsBinding.instance.addPostFrameCallback((_) => locationUtils.getCurrentLocation());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ProjectViewModel projectViewModel = Provider.of(context);
    return AppScaffold(
      isShowAppBar: true,
      showNewAppBar: true,
      showNewAppBarTitle: true,
      appBarTitle: TranslationBase.of(context).prescriptions,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          DoctorHeader(
            headerModel: HeaderModel(
              widget.prescriptions!.doctorName!,
              widget.prescriptions!.doctorID!,
              widget.prescriptions!.doctorImageURL!,
              widget.prescriptions!.speciality ?? [""],
              "",
              widget.prescriptions!.name!,
              DateUtil.convertStringToDate(widget.prescriptions!.appointmentDate!),
              DateUtil.formatDateToTime(DateUtil.convertStringToDate(widget.prescriptions!.appointmentDate!)),
              widget.prescriptions!.nationalityFlagURL!,
              widget.prescriptions!.doctorRate,
              widget.prescriptions!.actualDoctorRate,
              widget.prescriptions!.noOfPatientsRate,
              "",
            ),
            isNeedToShowButton: false,
          ),
          Expanded(
            child: ListView(
              physics: BouncingScrollPhysics(),
              padding: EdgeInsets.all(21),
              children: [
                Container(
                  padding: EdgeInsets.all(14),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10.0)),
                    boxShadow: [
                      BoxShadow(
                        color: Color(0xff000000).withOpacity(.05),
                        //spreadRadius: 5,
                        blurRadius: 27,
                        offset: Offset(0, -3),
                      ),
                    ],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Row(
                        children: <Widget>[
                          // InkWell(
                          //   child: Stack(
                          //     alignment: Alignment.center,
                          //     children: [
                          //       Container(
                          //         child: Image.network(
                          //           widget.prescriptionReport.imageSRCUrl,
                          //           fit: BoxFit.cover,
                          //           width: 48,
                          //           height: 49,
                          //         ),
                          //         margin: EdgeInsets.zero,
                          //         clipBehavior: Clip.antiAlias,
                          //         decoration: cardRadius(2000),
                          //       ),
                          //       Container(
                          //         child: Icon(
                          //           Icons.search,
                          //           size: 18,
                          //           color: Colors.white,
                          //         ),
                          //         padding: EdgeInsets.all(6),
                          //         decoration: containerRadius(Colors.black.withOpacity(0.3), 200),
                          //       )
                          //     ],
                          //   ),
                          //   onTap: () {
                          //     showZoomImageDialog(context, widget.prescriptionReport.imageSRCUrl);
                          //   },
                          // ),
                          // SizedBox(width: 12),
                          Expanded(
                            child: Text(
                              (widget.prescriptionReport!.itemDescription!.isNotEmpty ? widget.prescriptionReport!.itemDescription : widget.prescriptionReport!.itemDescriptionN ?? '')!
                                  .toLowerCase()
                                  .capitalizeFirstofEach,
                              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: -0.64),
                            ),
                          )
                        ],
                      ),
                      SizedBox(height: 12),
                      Table(border: TableBorder(horizontalInside: BorderSide(width: 1, color: Colors.black, style: BorderStyle.solid)), children: [
                        TableRow(
                          children: [
                            Utils.tableColumnTitle(TranslationBase.of(context).route, showDivider: false),
                            Utils.tableColumnTitle(TranslationBase.of(context).frequency, showDivider: false),
                            Utils.tableColumnTitle(TranslationBase.of(context).dailyDoses, showDivider: false),
                            Utils.tableColumnTitle(TranslationBase.of(context).duration, showDivider: false)
                          ],
                        ),
                        TableRow(
                          children: [
                            Utils.tableColumnValue(widget.prescriptionReport?.routeN ?? '', isLast: true, mProjectViewModel: projectViewModel),
                            Utils.tableColumnValue(widget.prescriptionReport?.frequencyN ?? '', isLast: true, mProjectViewModel: projectViewModel),
                            Utils.tableColumnValue(widget.prescriptionReport?.doseDailyQuantity.toString() ?? '', isLast: true, mProjectViewModel: projectViewModel),
                            Utils.tableColumnValue(widget.prescriptionReport?.days.toString() ?? '', isLast: true, mProjectViewModel: projectViewModel),
                          ],
                        ),
                      ]),
                      Text(
                        TranslationBase.of(context).remarks,
                        style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff2E303A), letterSpacing: -0.48),
                      ),
                      Text(
                        widget.prescriptionReport!.remarks!,
                        style: TextStyle(fontSize: 12, fontWeight: FontWeight.w600, color: Color(0xff575757), letterSpacing: -0.4, height: 16 / 10),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          Container(
            color: Colors.white,
            padding: EdgeInsets.only(top: 16, bottom: 16, right: 21, left: 21),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Expanded(
                  child: DefaultButton(
                    TranslationBase.of(context).availability,
                    () {
                      Navigator.push(
                        context,
                        FadePage(
                          page: PharmacyForPrescriptionsPage(
                            itemID: widget.prescriptionReport!.itemID,
                            prescriptionReport: widget.prescriptionReport,
                          ),
                        ),
                      );
                    },
                    iconData: Icons.location_on,
                    color: Color(0xff359846),
                  ),
                ),
                SizedBox(width: 10),
                Expanded(
                  child: DefaultButton(
                    hasReminder ? TranslationBase.of(context).cancelReminder : TranslationBase.of(context).addReminder,
                    () {
                      if (hasReminder) {
                        checkAndRemove(delete: true);
                      } else {
                        DateTime startDate = DateTime.now();
                        DateTime endDate = DateTime(startDate.year, startDate.month, startDate.day + widget.prescriptionReport!.days!);
                        showReminderDialog(
                          context,
                          endDate,
                          "",
                          widget.prescriptionReport!.itemID.toString(),
                          "",
                          "",
                          title: "${widget.prescriptionReport!.itemDescriptionN} Prescription Reminder",
                          description: "${widget.prescriptionReport!.itemDescriptionN} ${widget.prescriptionReport!.frequencyN} ${widget.prescriptionReport!.routeN} ",
                          onSuccess: () {
                            AppToast.showSuccessToast(message: TranslationBase.of(context).reminderSuccess);
                          },
                          isMultiAllowed: true,
                          onMultiDateSuccess: (int selectedIndex) {
                            setCalender(context, widget.prescriptionReport!.itemID.toString(), selectedIndex);
                          },
                        );
                        return;
                      }
                    },
                    iconData: Icons.notifications_active,
                    color: Color(0xffD02127),
                    fontSize: 13.0,
                    //textColor: Color(0xff2B353E),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  // checkAndRemove({bool delete = false}) async {
  //   final ios.CalendarPlugin _myPlugin = ios.CalendarPlugin();
  //   CalendarUtils calendarUtils = await CalendarUtils.getInstance();
  //   DateTime startEventsDate = Jiffy.parseFromDateTime(DateTime.now()).subtract(days: 30).dateTime;
  //   DateTime endEventsDate = Jiffy.parseFromDateTime(DateTime.now()).add(days: 120).dateTime;
  //   RetrieveEventsParams params = new RetrieveEventsParams(startDate: startEventsDate, endDate: endEventsDate);
  //
  //   if (calendarUtils.calendars != null) {
  //     print(calendarUtils.calendars);
  //     if (Platform.isAndroid) {
  //       Future.forEach(
  //           calendarUtils.calendars,
  //           (Calendar calender) => {
  //                 calendarUtils.retrieveEvents(calender.id!, params).then((value) {
  //                   Result<UnmodifiableListView<Event>> events = value;
  //                   events.data!.forEach((element) {
  //                     if (delete) {
  //                       if (element.title!.contains(widget.prescriptionReport!.itemDescriptionN!)) calendarUtils.deleteEvent(calender, element);
  //                       AppToast.showSuccessToast(message: TranslationBase.of(context).reminderCancelSuccess);
  //                       setState(() {
  //                         hasReminder = false;
  //                       });
  //                     } else {
  //                       if (element.title!.contains(widget.prescriptionReport!.itemDescriptionN!))
  //                         setState(() {
  //                           hasReminder = true;
  //                         });
  //                     }
  //                   });
  //                 }),
  //               });
  //     } else {
  //       List<ios.Calendar>? iosCall = await _myPlugin.getCalendars();
  //       Future.forEach(
  //         iosCall!,
  //         (ios.Calendar cal) async => {
  //           print(cal),
  //           calendarUtils.retrieveEvents(cal.id!, params).then((value) {
  //             Result<UnmodifiableListView<Event>> events = value;
  //             events.data!.forEach((element) {
  //               if (delete) {
  //                 if (element.title!.contains(widget.prescriptionReport!.itemDescriptionN!)) calendarUtils.deleteEvent(Calendar(id: cal.id, name: cal.name, accountName: cal.accountName), element);
  //                 AppToast.showSuccessToast(message: TranslationBase.of(context).reminderCancelSuccess);
  //                 setState(() {
  //                   hasReminder = false;
  //                 });
  //               } else {
  //                 if (element.title!.contains(widget.prescriptionReport!.itemDescriptionN!))
  //                   setState(() {
  //                     hasReminder = true;
  //                   });
  //               }
  //             });
  //           }),
  //         },
  //       );
  //     }
  //   }
  // }

  Future<void> checkAndRemove({bool delete = false}) async {
    final ios.CalendarPlugin _myPlugin = ios.CalendarPlugin();
    CalendarUtils calendarUtils = await CalendarUtils.getInstance();
    DateTime startEventsDate = Jiffy.parseFromDateTime(DateTime.now()).subtract(days: 30).dateTime;
    DateTime endEventsDate = Jiffy.parseFromDateTime(DateTime.now()).add(days: 120).dateTime;
    RetrieveEventsParams params = RetrieveEventsParams(startDate: startEventsDate, endDate: endEventsDate);

    if (calendarUtils.calendars != null) {
      if (Platform.isAndroid) {
        await processEvents(calendarUtils.calendars, calendarUtils, params, delete);
      } else {
        List<ios.Calendar>? iosCalendars = await _myPlugin.getCalendars();
        if (iosCalendars != null) {
          await processEvents(iosCalendars.map((cal) => Calendar(id: cal.id, name: cal.name, accountName: cal.accountName)).toList(), calendarUtils, params, delete);
        }
      }
    }
  }

  Future<void> processEvents(List<Calendar> calendars, calendarUtils, params, delete) async {
    for (var calendar in calendars) {
      Result<UnmodifiableListView<Event>> events = await calendarUtils.retrieveEvents(calendar.id!, params);
      for (var event in events.data!) {
        if (event.title!.contains(widget.prescriptionReport!.itemDescriptionN!)) {
          if (delete) {
            await calendarUtils.deleteEvent(calendar, event);
            AppToast.showSuccessToast(message: TranslationBase.of(context).reminderCancelSuccess);
            setState(() {
              hasReminder = false;
            });
          } else {
            setState(() {
              hasReminder = true;
            });
          }
        }
      }
    }
  }

  // cancelReminders() async {
  //   CalendarUtils calendarUtils = await CalendarUtils.getInstance();
  //   final ios.CalendarPlugin _myPlugin = ios.CalendarPlugin();
  //   DateTime startEventsDate = Jiffy.parseFromDateTime(DateTime.now()).subtract(days: 30).dateTime;
  //   DateTime endEventsDate = Jiffy.parseFromDateTime(DateTime.now()).add(days: 120).dateTime;
  //   RetrieveEventsParams params = RetrieveEventsParams(startDate: startEventsDate, endDate: endEventsDate);
  //
  //   if (Platform.isAndroid) {
  //     Future.forEach(
  //         calendarUtils.calendars,
  //         (Calendar calender) => {
  //               calendarUtils.retrieveEvents(calender.id!, params).then((value) {
  //                 Result<UnmodifiableListView<Event>> events = value;
  //                 events.data!.forEach((element) {
  //                   if (element.title!.contains(widget.prescriptionReport!.itemDescriptionN!)) calendarUtils.deleteEvent(calender, element);
  //                 });
  //               }),
  //             });
  //   } else {
  //     List<ios.Calendar>? iosCal = await _myPlugin.getCalendars();
  //     Future.forEach(
  //         iosCal!,
  //         (ios.Calendar cale) async => {
  //               calendarUtils.retrieveEvents(cale.id!, params).then((value) {
  //                 Result<UnmodifiableListView<Event>> events = value;
  //                 events.data!.forEach((element) {
  //                   print(element.title);
  //                   if (element.title!.contains(widget.prescriptionReport!.itemDescriptionN!))
  //                     calendarUtils.deleteEvent(
  //                         Calendar(
  //                           id: cale.id,
  //                           name: cale.name,
  //                           accountName: cale.accountName,
  //                         ),
  //                         element);
  //                 });
  //               }),
  //             });
  //     AppToast.showSuccessToast(message: TranslationBase.of(context).reminderCancelSuccess);
  //     setState(() {
  //       hasReminder = false;
  //     });
  //   }
  // }

  setCalender(BuildContext context, String eventId, int reminderIndex) async {
    DateTime actualDate = DateTime(DateTime.now().year, DateTime.now().month, DateTime.now().day, 8, 0);
    if (widget.prescriptionReport?.frequencyNumber == null) widget.prescriptionReport!.frequencyNumber = 2; //Some time frequency number is null so by default will be 2

    int remainingDays = widget.prescriptionReport!.days! -
        (Jiffy.parseFromDateTime(DateTime.now()).diff(Jiffy.parseFromDateTime(DateUtil.convertStringToDate(widget.prescriptionReport!.orderDate!)), unit: Unit.day) as int);
    if (remainingDays.isNegative) {
      Utils.showErrorToast("Prescription date has been already passed you can not add a reminder for this prescription.");
      return;
    }
    CalendarUtils calendarUtils = await CalendarUtils.getInstance();
    GifLoaderDialogUtils.showMyDialog(context);

    try {
      for (int i = 0; i < remainingDays; i++) {
        //event for number of days.
        for (int j = 0; j < widget.prescriptionReport!.frequencyNumber!; j++) {
          // event for number of times per day.
          if (j != 0) {
            actualDate.add(new Duration(hours: 8)); // 8 hours addition for daily dose.
          }
          //Time subtraction from actual reminder time. like before 30, or 1 hour.
          if (reminderIndex == 0) {
            // Before 30 mints
            actualDate = Jiffy.parseFromDateTime(actualDate).subtract(minutes: 30).dateTime;
            // dateTime.add(new Duration(minutes: -30));
          } else if (reminderIndex == 1) {
            // Before 1 hour
            // dateTime.add(new Duration(minutes: -60));
            actualDate = Jiffy.parseFromDateTime(actualDate).subtract(hours: 1).dateTime;
          } else if (reminderIndex == 2) {
            // Before 1 hour and 30 mints
            // dateTime.add(new Duration(minutes: -90));
            actualDate = Jiffy.parseFromDateTime(actualDate).subtract(hours: 1, minutes: 30).dateTime;
          } else if (reminderIndex == 3) {
            // Before 2 hours
            // dateTime.add(new Duration(minutes: -120));
            actualDate = Jiffy.parseFromDateTime(actualDate).subtract(hours: 2).dateTime;
          }

          calendarUtils.createOrUpdateEvent(
            title: "${widget.prescriptionReport!.itemDescriptionN} Prescription Reminder",
            description: "${widget.prescriptionReport!.itemDescriptionN} ${widget.prescriptionReport!.frequencyN} ${widget.prescriptionReport!.routeN} ",
            scheduleDateTime: actualDate,
            eventId: eventId + (i.toString() + j.toString()), //event id with  varitions
          );

          actualDate = DateTime(actualDate.year, actualDate.month, actualDate.day, 8, 0);
        }
        actualDate = Jiffy.parseFromDateTime(actualDate).add(days: 1).dateTime;
        print(actualDate);
      }
    } catch (ex) {
      print("catch:$ex");
    }

    AppToast.showSuccessToast(message: TranslationBase.of(context).reminderSuccess);
    Future.delayed(Duration(seconds: 2), () {
      GifLoaderDialogUtils.hideDialog(context);
    });
    setState(() {
      hasReminder = true;
    });
  }
}
