import 'dart:convert';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/app_strings/app_asset.dart';
import 'package:test_sa/controllers/providers/api/service_requests_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/string_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/models/enums/work_order_next_step.dart';
import 'package:test_sa/models/helper_data_models/maintenance_request/activity_maintenance_model.dart';
import 'package:test_sa/models/helper_data_models/spare_part/activity_spare_part_model.dart';
import 'package:test_sa/models/helper_data_models/workorder/work_order_helper_models.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/new_models/work_order_detail_model.dart';
import 'package:test_sa/modules/cm_module/cm_detail_provider.dart';
import 'package:test_sa/modules/cm_module/cm_request_utils.dart';
import 'package:test_sa/modules/cm_module/views/forms/maintenance_request/maintenance_request_main.dart';
import 'package:test_sa/modules/cm_module/views/forms/spare_part/spare_part_request.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/app_lazy_loading.dart';
import 'package:test_sa/new_views/common_widgets/app_text_form_field.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/providers/service_request_providers/reject_reason_provider.dart';
import 'package:test_sa/providers/work_order/need_visit_reminder_time_provider.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';
import 'package:test_sa/views/widgets/date_and_time/time_picker.dart';
import 'package:test_sa/views/widgets/e_signature/e_signature.dart';
import 'package:test_sa/views/widgets/loaders/app_loading.dart';

class ServiceRequestBottomSheet {
  static buildBottomSheetParent({required BuildContext context, required Widget childWidget, bool? isDismissible}) {
    return showModalBottomSheet(
      context: context,
      useSafeArea: true,
      isScrollControlled: true,
      isDismissible: isDismissible ?? true,
      backgroundColor: AppColor.bottomSheetColor(context),
      builder: (context) => SingleChildScrollView(
        child: SafeArea(child: childWidget),
      ).bottomSheetContainer(context),
    );
  }

  static Future fixRemotelyBottomSheet({required BuildContext context}) {
    TextEditingController _workingHoursController = TextEditingController();
    TextEditingController _commentController = TextEditingController();

    return buildBottomSheetParent(
        context: context,
        childWidget: Consumer<CMDetailProvider>(builder: (context, CMDetailProvider requestDetailProvider, child) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const SizedBox().indicatorWidget(),
              16.height,
              Align(
                alignment: AlignmentDirectional.centerStart,
                child: context.translation.fillDetails.bottomSheetHeadingTextStyle(context),
              ),
              16.height,
              ADatePicker(
                label: context.translation.startDate,
                hideShadow: true,
                // height: 60.toScreenHeight,
                backgroundColor: AppColor.neutral100,
                date: requestDetailProvider.fixRemotelyHelperModel?.startDate,
                formatDateWithTime: true,
                onDatePicker: (selectedDate) {
                  showThemedTimePicker(
                    context: context,
                    initialTime: TimeOfDay.now(),
                  ).then((selectedTime) {
                    // Handle the selected date and time here.
                    if (selectedTime != null) {
                      DateTime selectedDateTime = DateTime(
                        selectedDate.year,
                        selectedDate.month,
                        selectedDate.day,
                        selectedTime.hour,
                        selectedTime.minute,
                      );
                      requestDetailProvider.fixRemotelyHelperModel?.startDate = selectedDateTime;
                      requestDetailProvider.fixRemotelyHelperModel?.endDate = null;
                      requestDetailProvider.updateFixRemotelyHelperModel(requestDetailProvider.fixRemotelyHelperModel);
                      _workingHoursController.clear();
                      CMRequestUtils.calculateAndAssignWorkingHours(
                        startTime: requestDetailProvider.fixRemotelyHelperModel?.startDate,
                        endTime: requestDetailProvider.fixRemotelyHelperModel?.endDate,
                        workingHoursController: _workingHoursController,
                        updateModel: (hours) {
                          requestDetailProvider.fixRemotelyHelperModel?.workingHour = hours;
                        },
                      );
                      // serviceRequestProvider.updateCurrentSelectedRequest(serviceRequestProvider.currentSelectedRequest);
                    }
                  });
                },
              ),
              8.height,
              ADatePicker(
                label: context.translation.endDate,
                hideShadow: true,
                // height: 60.toScreenHeight,
                backgroundColor: AppColor.neutral100,
                date: requestDetailProvider.fixRemotelyHelperModel?.endDate,
                formatDateWithTime: true,
                onDatePicker: (selectedDate) {
                  showThemedTimePicker(
                    context: context,
                    initialTime: TimeOfDay.now(),
                  ).then((selectedTime) {
                    // Handle the selected date and time here.
                    if (selectedTime != null) {
                      DateTime selectedDateTime = DateTime(
                        selectedDate.year,
                        selectedDate.month,
                        selectedDate.day,
                        selectedTime.hour,
                        selectedTime.minute,
                      );

                      if (requestDetailProvider.fixRemotelyHelperModel!.startDate != null && selectedDateTime.isBefore(requestDetailProvider.fixRemotelyHelperModel!.startDate!)) {
                        "End Date time must be greater then start date".showToast;
                        return;
                      }
                      requestDetailProvider.fixRemotelyHelperModel?.endDate = selectedDateTime;
                      requestDetailProvider.updateFixRemotelyHelperModel(requestDetailProvider.fixRemotelyHelperModel);
                      CMRequestUtils.calculateAndAssignWorkingHours(
                        startTime: requestDetailProvider.fixRemotelyHelperModel?.startDate,
                        endTime: requestDetailProvider.fixRemotelyHelperModel?.endDate,
                        workingHoursController: _workingHoursController,
                        updateModel: (hours) {
                          requestDetailProvider.fixRemotelyHelperModel?.workingHour = hours;
                        },
                      );
                    }
                  });
                },
              ),
              8.height,
              AppTextFormField(
                labelText: context.translation.workingHours,
                textInputType: TextInputType.number,
                enable: false,
                controller: _workingHoursController,
                labelStyle: AppTextStyles.textFieldLabelStyle,
                showWithoutDecoration: true,
                backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral100,
                alignLabelWithHint: true,
                onChange: (text) {
                  if (text.isNotEmpty) {
                    requestDetailProvider.fixRemotelyHelperModel?.workingHour = int.parse(text);
                  }
                },
                onSaved: (text) {
                  if (text.isNotEmpty) {
                    requestDetailProvider.fixRemotelyHelperModel?.workingHour = int.parse(text);
                  }
                },
              ),
              8.height,
              AppTextFormField(
                labelText: context.translation.comments,
                showSpeechToText: true,
                controller: _commentController,
                textInputType: TextInputType.multiline,
                labelStyle: AppTextStyles.textFieldLabelStyle,
                showWithoutDecoration: true,
                backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral100,
                alignLabelWithHint: true,
                onChange: (text) {
                  requestDetailProvider.fixRemotelyHelperModel?.comment = text;
                },
                onSaved: (text) {
                  requestDetailProvider.fixRemotelyHelperModel?.comment = text;
                },
              ),
              16.height,
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Expanded(
                    child: AppFilledButton(
                      label: context.translation.cancel,
                      loading: false,
                      buttonColor: Colors.transparent,
                      showBorder: true,
                      textColor: AppColor.black20,
                      onPressed: () async {
                        Navigator.pop(context);
                      },
                    ),
                  ),
                  10.width,
                  Expanded(
                    child: AppFilledButton(
                      label: context.translation.fixed,
                      buttonColor: AppColor.green70,
                      loading: false,
                      onPressed: () async {
                        if (requestDetailProvider.fixRemotelyHelperModel?.startDate == null && requestDetailProvider.fixRemotelyHelperModel?.endDate == null) {
                          "Please Select start and end date".showToast;
                          return;
                        }
                        requestDetailProvider.fixRemotelyHelperModel?.workOrderId = requestDetailProvider.currentWorkOrder?.data?.requestId;
                        requestDetailProvider.engineerFixRemotely();
                        Navigator.pop(context);
                        const SizedBox().flushBar(context: context, title: '', message: context.translation.youMarkedThisIssueAsFixedWaitingForTheRequesterToConfirm);
                      },
                    ),
                  ),
                ],
              ),
              16.height,
            ],
          );
        }));
  }

  static Future initialVisitBottomSheet({required BuildContext context}) {
    TextEditingController _commentController = TextEditingController();

    return buildBottomSheetParent(
        context: context,
        childWidget: Consumer<CMDetailProvider>(builder: (context, requestDetailProvider, child) {
          if (requestDetailProvider.needVisitHelperModel?.comment != null) {
            _commentController.text = requestDetailProvider.needVisitHelperModel!.comment!;
          }
          return Column(
            children: [
              const SizedBox().indicatorWidget(),
              8.height,
              Align(
                alignment: AlignmentDirectional.centerStart,
                child: context.translation.setVisitDate.bottomSheetHeadingTextStyle(context),
              ),
              15.height,
              ADatePicker(
                label: context.translation.visitDate,
                hideShadow: true,
                backgroundColor: AppColor.neutral100,
                date: requestDetailProvider.needVisitHelperModel?.visitDate,
                formatDateWithTime: true,
                onDatePicker: (selectedDate) {
                  showThemedTimePicker(
                    context: context,
                    initialTime: TimeOfDay.now(),
                  ).then((selectedTime) {
                    // Handle the selected date and time here.
                    if (selectedTime != null) {
                      DateTime selectedDateTime = DateTime(
                        selectedDate.year,
                        selectedDate.month,
                        selectedDate.day,
                        selectedTime.hour,
                        selectedTime.minute,
                      );
                      requestDetailProvider.needVisitHelperModel?.visitDate = selectedDateTime;
                      requestDetailProvider.updateNeedVisitHelperModel(requestDetailProvider.needVisitHelperModel);
                    }
                  });
                },
              ),
              8.height,
              AppTextFormField(
                labelText: context.translation.comments,
                controller: _commentController,
                backgroundColor: AppColor.neutral100,
                labelStyle: AppTextStyles.textFieldLabelStyle,
                showShadow: false,
                showSpeechToText: true,
                textInputType: TextInputType.multiline,
                alignLabelWithHint: true,
                onChange: (text) {
                  requestDetailProvider.needVisitHelperModel?.comment = text;
                },
                onSaved: (text) {
                  requestDetailProvider.needVisitHelperModel?.comment = text;
                },
              ),
              12.height,
              AppFilledButton(
                label: context.translation.save,
                buttonColor: AppColor.primary10,
                loading: false,
                onPressed: () async {
                  if (requestDetailProvider.needVisitHelperModel?.visitDate == null) {
                    "Please select visit date".showToast;
                    return;
                  }
                  if (requestDetailProvider.currentWorkOrder?.data?.nextStep!.workOrderNextStepEnum == WorkOrderNextStepEnum.eArrived) {
                    requestDetailProvider.needVisitHelperModel?.workOrderId = requestDetailProvider.currentWorkOrder!.data!.requestId;
                    requestDetailProvider.engineerUpdateNeedVisit();
                    try {
                      DateTime visitDateTime = requestDetailProvider.needVisitHelperModel!.visitDate!;
                      int? reminderMinutes = requestDetailProvider.currentWorkOrder!.data!.setReminder?.value;
                      DateTime updatedDateTime = visitDateTime.subtract(Duration(minutes: reminderMinutes ?? 0));
                      if (updatedDateTime.isAfter(DateTime.now())) {
                        // ServiceRequestUtils.scheduleNotification(context: context, scheduleDateTime: updatedDateTime);
                        CMRequestUtils.addOrUpdateEventToCalendar(
                            context: context,
                            start: updatedDateTime,
                            end: visitDateTime,
                            title: context.translation.needAVisit,
                            workOrderNumber: requestDetailProvider.currentWorkOrder!.data!.workOrderNo!);
                      } else {
                        // "Visit date is before the reminder time selected".showToast;
                      }
                    } catch (e) {
                      log('error $e');
                    }
                    Navigator.pop(context);
                  } else {
                    requestDetailProvider.needVisitHelperModel?.workOrderId = requestDetailProvider.currentWorkOrder!.data!.requestId;
                    requestDetailProvider.engineerNeedVisit();
                    getReminderTimeList(context: context);
                    Navigator.pop(context);
                    initialVisitReminderBottomSheet(context: context);
                  }

                  //
                },
              ),
              16.height,
            ],
          );
        }));
  }

  static Future<void> getReminderTimeList({required BuildContext context}) async {
    NeedVisitReminderTimeProvider timeProvider = Provider.of<NeedVisitReminderTimeProvider>(context, listen: false);
    timeProvider.reset();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      timeProvider.getData();
    });
  }

  static Future initialVisitReminderBottomSheet({required BuildContext context, Lookup? reminder}) {
    Lookup selectedReminderTime = reminder ?? Lookup();
    Widget reminderTimeWidget({required BuildContext context}) {
      return Consumer<NeedVisitReminderTimeProvider>(builder: (cxt, snapshot, _) {
        if (snapshot.loading) {
          return const ALoading();
        }

        return StatefulBuilder(
          builder: (context, setState) {
            return Wrap(
              direction: Axis.vertical,
              runSpacing: 8,
              spacing: 20,
              children: [
                for (var element in snapshot.items)
                  Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      SizedBox(
                        width: 24,
                        height: 24,
                        child: Radio<Lookup>(
                          value: element,
                          activeColor: Colors.red,
                          fillColor: MaterialStateColor.resolveWith((states) {
                            if (states.contains(MaterialState.selected)) return AppColor.primary10;
                            return AppColor.neutral130;
                          }),
                          groupValue: selectedReminderTime,
                          onChanged: (Lookup? value) {
                            setState(() {
                              selectedReminderTime = value!;
                            });
                          },
                        ),
                      ),
                      8.width,
                      Text(element.name ?? '', style: AppTextStyles.bodyText.copyWith(color: AppColor.neutral120)),
                    ],
                  )
              ],
            );
          },
        ).toShimmer(isShow: snapshot.loading, context: context);
      });
    }

    return buildBottomSheetParent(
      context: context,
      childWidget: Consumer<CMDetailProvider>(
        builder: (context, requestDetailProvider, child) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SizedBox().indicatorWidget().center,
              8.height,
              Align(
                alignment: AlignmentDirectional.centerStart,
                child: context.translation.doYouWantToSetReminder.bottomSheetHeadingTextStyle(context),
              ),
              8.height,
              Align(
                alignment: AlignmentDirectional.centerStart,
                child: context.translation.youCanSetTheReminderInAlarmToRemindYouBeforeVisit.bodyText2(context),
              ),
              30.height,
              reminderTimeWidget(context: context),
              30.height,
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Expanded(
                    child: AppFilledButton(
                      label: context.translation.cancel,
                      buttonColor: AppColor.white60,
                      textColor: AppColor.black10,
                      loading: false,
                      onPressed: () async {
                        Navigator.pop(context);
                      },
                    ),
                  ),
                  12.width,
                  Expanded(
                    child: AppFilledButton(
                      label: context.translation.setReminder,
                      buttonColor: AppColor.primary10,
                      loading: false,
                      onPressed: () async {
                        requestDetailProvider.engineerSetReminder(workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId!, reminderId: selectedReminderTime.id!);
                        try {
                          DateTime visitDateTime = DateTime.parse(requestDetailProvider.currentWorkOrder!.data!.needAVisitDateTime.toString());
                          DateTime updatedDateTime = visitDateTime.subtract(Duration(minutes: selectedReminderTime.value ?? 0));
                          if (updatedDateTime.isAfter(DateTime.now())) {
                            CMRequestUtils.addOrUpdateEventToCalendar(
                                context: context,
                                start: updatedDateTime,
                                end: visitDateTime,
                                title: context.translation.needAVisit,
                                workOrderNumber: requestDetailProvider.currentWorkOrder!.data!.workOrderNo!);
                            // uncommit this to add schedule notification need to confirm what to do in case of update....
                            // ServiceRequestUtils.scheduleOrUpdateNotification(context: context, scheduleDateTime: updatedDateTime,workOrderId: requestDetailProvider.currentWorkOrder!.data!.workOrderNo!);
                          } else {
                            "Visit date is before the reminder time selected".showToast;
                          }
                        } catch (e) {
                          log('error $e');
                        }
                        Navigator.pop(context);
                      },
                    ),
                  ),
                ],
              ),
              16.height,
            ],
          );
        },
      ),
    );
  }

  static Future getQRCodeBottomSheet({required BuildContext context}) async {
    // Show the loading dialog while fetching QR code
    showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
    CMDetailProvider requestDetailProvider = Provider.of<CMDetailProvider>(context, listen: false);
    String? base64String = await requestDetailProvider.getQrCode(workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId ?? 0);
    Navigator.pop(context);

    if (base64String != null) {
      Uint8List bytes = base64Decode(base64String);
      bool isLoading = false;

      return buildBottomSheetParent(
        context: context,
        childWidget: StatefulBuilder(
          builder: (context, setState) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox().indicatorWidget().center,
                8.height,
                Align(
                  alignment: AlignmentDirectional.centerStart,
                  child: context.translation.qrCode.bottomSheetHeadingTextStyle(context),
                ),
                8.height,
                Align(
                  alignment: AlignmentDirectional.centerStart,
                  child: context.translation.provideQrCodeToEngineer.bodyText(context),
                ),
                12.height,
                SizedBox(
                  height: 296.toScreenHeight,
                  child: Center(
                    child: isLoading
                        ? const ALoading() // Show loader while fetching the new QR code
                        : Image.memory(
                            bytes, // Displaying the QR code from base64
                            fit: BoxFit.contain, // Ensure the image fits well in the dialog
                            errorBuilder: (context, error, stackTrace) {
                              return const Icon(Icons.error, color: Colors.red);
                            },
                          ),
                  ),
                ),
                12.height,
                Center(
                  child: InkWell(
                    onTap: () async {
                      // Set loading state and call API to get the new QR code
                      setState(() {
                        isLoading = true;
                      });

                      // Fetch the new QR code
                      String? newBase64String = await requestDetailProvider.getQrCode(
                        workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId ?? 0,
                      );

                      // Decode the new QR code and update the state
                      if (newBase64String != null) {
                        setState(() {
                          bytes = base64Decode(newBase64String);
                          isLoading = false;
                        });
                      } else {
                        setState(() {
                          isLoading = false; // Stop loader if fetching fails
                        });
                      }
                    },
                    child: Text(
                      context.translation.refreshQrCode,
                      style: TextStyle(
                        color: AppColor.primary10,
                        fontWeight: FontWeight.w500,
                        fontSize: 12.toScreenWidth,
                        decorationColor: AppColor.primary10,
                        decoration: TextDecoration.underline,
                      ),
                    ),
                  ),
                ),
                16.height,
                AppFilledButton(
                  label: context.translation.close,
                  // maxWidth: true,
                  textColor: AppColor.black20,
                  buttonColor: AppColor.white30,
                  onPressed: () async {
                    Navigator.pop(context);
                  },
                ),
                16.height,
              ],
            );
          },
        ),
      );
    } else {
      print('Failed to get the QR code');
    }
  }

  static Future rejectRequestBottomSheet({required BuildContext context}) {
    TextEditingController _commentController = TextEditingController();
    return buildBottomSheetParent(
        context: context,
        childWidget: Consumer<CMDetailProvider>(builder: (context, requestDetailProvider, child) {
          return Column(
            children: [
              const SizedBox().indicatorWidget(),
              Align(
                alignment: AlignmentDirectional.centerStart,
                child: context.translation.rejectionReason.heading4(context).paddingOnly(top: 12),
              ),
              16.height,
              SingleItemDropDownMenu<Lookup, RejectReasonProvider>(
                context: context,
                title: context.translation.reason,
                backgroundColor: AppColor.neutral100,
                showShadow: false,
                initialValue: requestDetailProvider.engineerRejectHelperModel?.rejectionReason,
                onSelect: (value) {
                  if (value != null) {
                    requestDetailProvider.engineerRejectHelperModel?.rejectionReason = value;
                    requestDetailProvider.updateEngineerRejectHelperModel(requestDetailProvider.engineerRejectHelperModel);
                  }
                },
              ),
              12.height,
              AppTextFormField(
                backgroundColor: AppColor.neutral100,
                labelText: context.translation.comments,
                controller: _commentController,
                textInputType: TextInputType.multiline,
                alignLabelWithHint: true,
                showSpeechToText: true,
                showShadow: false,
                labelStyle: AppTextStyles.textFieldLabelStyle,
                onChange: (text) {
                  requestDetailProvider.engineerRejectHelperModel?.feedback = text;
                },
                onSaved: (text) {
                  requestDetailProvider.engineerRejectHelperModel?.feedback = text;
                  requestDetailProvider.updateEngineerRejectHelperModel(requestDetailProvider.engineerRejectHelperModel);
                },
              ),
              16.height,
              AppFilledButton(
                label: context.translation.reject,
                maxWidth: true,
                buttonColor: Colors.white54,
                textColor: AppColor.red30,
                showBorder: true,
                loading: requestDetailProvider.isLoading,
                onPressed: () async {
                  requestDetailProvider.engineerRejectHelperModel?.workOrderId = requestDetailProvider.currentWorkOrder?.data?.requestId;
                  requestDetailProvider.engineerRejectWorkOrder();
                  Navigator.pop(context, true);
                },
              ),
              16.height,
            ],
          );
        }));
  }

  static Future activityTypeBottomSheet({required BuildContext context}) {
    final List<Map<String, String>> items = [
      {'heading': context.translation.requestSparePart, 'subHeading': context.translation.requestSparePartForYourAsset, 'icon': AppAsset.sparePartIcon},
      {'heading': context.translation.addNewActivity, 'subHeading': context.translation.addNewActivityToYourWorkOrder, 'icon': AppAsset.maintenanceIcon},
    ];

    Widget customListItem({required BuildContext context, required String icon, required String heading, required String subHeading, required VoidCallback onTap}) {
      return GestureDetector(
          onTap: onTap, // Handles the tap
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start, // Align items at the top
            children: [
              // Icon Section
              icon.toSvgAsset(width: 26, color: AppColor.neutral120, height: 29).paddingOnly(top: 8),
              14.width,
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      heading,
                      style: AppTextStyles.heading6.copyWith(color: AppColor.textColor(context)),
                    ),
                    7.height,
                    Text(
                      subHeading,
                      style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral120),
                    ),
                  ],
                ).paddingOnly(end: 50),
              ),
            ],
          ).toShadowContainer(context));
    }

    void onItemTap({required int index, required BuildContext context}) {
      switch (index) {
        case 0:
          Provider.of<CMDetailProvider>(context, listen: false).sparePartHelperModel = SparePartHelperModel();
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => const SparePartRequest()),
          );
          break;
        case 1:
          CMDetailProvider requestDetailProvider = Provider.of<CMDetailProvider>(context, listen: false);
          requestDetailProvider.activityMaintenanceHelperModel = ActivityMaintenanceHelperModel(
            workOrderId: requestDetailProvider.currentWorkOrder?.data?.requestId,
            id: 0,
            assignedEmployee: requestDetailProvider.currentWorkOrder?.data?.assignedEmployee,
          );
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => MaintenanceRequestForm()),
          );
          break;
      }
    }

    return buildBottomSheetParent(
        context: context,
        childWidget: Consumer<ServiceRequestsProvider>(builder: (context, serviceRequestProvider, child) {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const SizedBox().indicatorWidget(),
              8.height,
              Align(
                alignment: AlignmentDirectional.centerStart,
                child: context.translation.selectAction.bottomSheetHeadingTextStyle(context),
              ),
              // 16.height,
              ListView.separated(
                shrinkWrap: true,
                padding: const EdgeInsets.only(top: 16, bottom: 16),
                itemCount: items.length,
                physics: const NeverScrollableScrollPhysics(),
                separatorBuilder: (cxt, index) => 12.height,
                itemBuilder: (context, index) {
                  final item = items[index];
                  return customListItem(
                      icon: item['icon']!,
                      heading: item['heading']!,
                      subHeading: item['subHeading']!,
                      context: context,
                      onTap: () {
                        onItemTap(index: index, context: context);
                      });
                },
              ),
            ],
          );
        }));
  }

  static Future actionBottomSheet({required BuildContext context, required String title, String? button1Text, String? button2Text, VoidCallback? button1Tap, VoidCallback? button2Tap}) {
    return buildBottomSheetParent(
        context: context,
        childWidget: Consumer<ServiceRequestsProvider>(builder: (context, serviceRequestProvider, child) {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const SizedBox().indicatorWidget(),
              8.height,
              Align(
                alignment: AlignmentDirectional.centerStart,
                child: title.bottomSheetHeadingTextStyle(context),
              ),
              41.height,
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  AppFilledButton(
                    label: button1Text ?? context.translation.no,
                    loading: false,
                    buttonColor: AppColor.white60,
                    textColor: AppColor.black10,
                    onPressed: button1Tap ??
                        () async {
                          Navigator.pop(context);
                        },
                  ).expanded,
                  12.width,
                  AppFilledButton(
                    label: context.translation.yes,
                    buttonColor: AppColor.primary10,
                    loading: false,
                    onPressed: button2Tap,
                  ).expanded,
                ],
              )
            ],
          );
        }));
  }

  static Future addAnotherSpareRequestBottomSheet({required BuildContext context}) {
    return buildBottomSheetParent(
      context: context,
      childWidget: Consumer<ServiceRequestsProvider>(
        builder: (context, serviceRequestProvider, child) {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const SizedBox().indicatorWidget(),
              8.height,
              Align(
                alignment: AlignmentDirectional.centerStart,
                child: context.translation.doYouWantToCreateAnotherSparePartRequest.bottomSheetHeadingTextStyle(context),
              ),
              41.height,
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  AppFilledButton(
                    label: context.translation.no,
                    loading: false,
                    showBorder: true,
                    buttonColor: AppColor.noButtonColor(context),
                    textColor: AppColor.labelTextStyleColor(context),
                    // buttonColor: AppColor.white60,
                    // textColor: AppColor.black10,
                    onPressed: () async {
                      Navigator.pop(context);
                    },
                  ).expanded,
                  12.width,
                  AppFilledButton(
                    label: context.translation.yes,
                    buttonColor: AppColor.primary10,
                    loading: false,
                    onPressed: () {
                      Navigator.pop(context);
                      Provider.of<CMDetailProvider>(context, listen: false).sparePartHelperModel = SparePartHelperModel();
                      Navigator.pushReplacement(
                        context,
                        MaterialPageRoute(builder: (context) => const SparePartRequest()),
                      );
                    },
                  ).expanded,
                ],
              ),
              16.height,
            ],
          );
        },
      ),
    );
  }

  static bool validateAssetSituation(CMDetailProvider requestDetailProvider) {
    // if (requestDetailProvider.engineerUpdateWorkOrderHelperModel!.equipmentStatus != null) {
    //   if (requestDetailProvider.engineerUpdateWorkOrderHelperModel!.equipmentStatus!.value == 1 || requestDetailProvider.engineerUpdateWorkOrderHelperModel!.equipmentStatus!.value == 2) {
    //     if (requestDetailProvider.engineerUpdateWorkOrderHelperModel!.returnToService == null) {
    //       Fluttertoast.showToast(msg: "Return to service is required ", toastLength: Toast.LENGTH_LONG);
    //       return false;
    //     }
    //   }
    // }
    return true;
  }

  static Future feedBackBottomSheet({required BuildContext context}) {
    String feedback = '';
    TextEditingController _commentController = TextEditingController();
    return buildBottomSheetParent(
        context: context,
        childWidget: Consumer<CMDetailProvider>(builder: (context, CMDetailProvider requestDetailProvider, child) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const SizedBox().indicatorWidget(),
              8.height,
              Align(
                alignment: AlignmentDirectional.centerStart,
                child: context.translation.feedBack.bottomSheetHeadingTextStyle(context),
              ),
              21.height,
              AppTextFormField(
                labelText: context.translation.comments,
                controller: _commentController,
                textInputType: TextInputType.multiline,
                labelStyle: AppTextStyles.textFieldLabelStyle,
                showWithoutDecoration: true,
                showSpeechToText: true,
                backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral100,
                alignLabelWithHint: true,
                onChange: (text) {
                  feedback = text;
                },
                onSaved: (text) {
                  feedback = text;
                },
              ),
              16.height,
              AppFilledButton(
                label: context.translation.fixed,
                buttonColor: AppColor.green70,
                loading: false,
                onPressed: () {
                  if (feedback.isEmpty) {
                    "Please provide feedback".showToast;
                    return;
                  }
                  Navigator.pop(context);
                  requestDetailProvider.engineerMarkAsFixed(workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId!, feedback: feedback);
                },
              ),
            ],
          );
        }));
  }

  static Future nurseRejectBackBottomSheet({required BuildContext context}) {
    String feedback = '';
    TextEditingController _feedBackController = TextEditingController();
    return buildBottomSheetParent(
        context: context,
        childWidget: Consumer<CMDetailProvider>(builder: (context, CMDetailProvider requestDetailProvider, child) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const SizedBox().indicatorWidget(),
              8.height,
              Align(
                alignment: AlignmentDirectional.centerStart,
                child: context.translation.rejectionReason.bottomSheetHeadingTextStyle(context),
              ),
              21.height,
              AppTextFormField(
                labelText: context.translation.comments,
                controller: _feedBackController,
                showSpeechToText: true,
                textInputType: TextInputType.multiline,
                labelStyle: AppTextStyles.textFieldLabelStyle,
                showWithoutDecoration: true,
                backgroundColor: context.isDark ? AppColor.neutral20 : AppColor.neutral100,
                alignLabelWithHint: true,
                onChange: (text) {
                  feedback = text;
                },
                onSaved: (text) {
                  feedback = text;
                },
              ),
              16.height,
              AppFilledButton(
                label: context.translation.reject,
                maxWidth: true,
                buttonColor: Colors.white54,
                textColor: AppColor.red30,
                showBorder: true,
                onPressed: () {
                  if (feedback.isNotEmpty) {
                    requestDetailProvider.nurseActionHelperModel = NurseActionHelperModel(
                      workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId,
                      feedback: feedback,
                    );
                    requestDetailProvider.nurseReject();
                    Navigator.pop(context);
                    if (requestDetailProvider.currentWorkOrder!.data!.requestId != null) {
                      requestDetailProvider.getWorkOrderById(id: requestDetailProvider.currentWorkOrder!.data!.requestId!);
                    }
                  }
                  // Navigator.pop(context);
                  // requestDetailProvider.engineerMarkAsFixed(workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId!, feedback: feedback);
                },
              ),
            ],
          );
        }));
  }

  static Future nurseTakeActionBottomSheet({required BuildContext context}) {
    bool acknowledge = false;
    Uint8List? newSignature;
    String? nurseSignature;
    return buildBottomSheetParent(
        context: context,
        childWidget: Consumer<CMDetailProvider>(builder: (context, CMDetailProvider requestDetailProvider, child) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const SizedBox().indicatorWidget(),
              8.height,
              Align(
                alignment: AlignmentDirectional.centerStart,
                child: context.translation.pleaseConfirmTheIssueHasBeenResolved.bottomSheetHeadingTextStyle(context),
              ),
              10.height,
              StatefulBuilder(
                builder: (context, setState) {
                  return Column(
                    children: [
                      Row(
                        children: [
                          InkWell(
                            child: acknowledge
                                ? const Icon(
                                    Icons.check_box,
                                    color: AppColor.primary10,
                                  )
                                : const Icon(
                                    Icons.check_box_outline_blank,
                                    color: AppColor.neutral120,
                                  ),
                            onTap: () {
                              setState(() {
                                acknowledge = !acknowledge;
                              });
                            },
                          ),
                          6.width,
                          Flexible(
                            child: context.translation.nurseAcknowledge.bodyText(context).custom(color: context.isDark ? AppColor.primary50 : AppColor.neutral120),
                          ),
                        ],
                      ),
                      17.height,
                      ESignature(
                        title: '',
                        oldSignature: '',
                        newSignature: newSignature,
                        backgroundColor: AppColor.neutral100,
                        showShadow: false,
                        onChange: (signature) {
                          if (signature == null || signature.isEmpty) return;
                          setState(() {
                            newSignature = signature;
                            nurseSignature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
                          });
                        },
                        onSaved: (signature) {
                          if (signature == null || signature.isEmpty) return;
                          setState(() {
                            newSignature = signature;
                            nurseSignature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
                          });
                        },
                      ),
                    ],
                  );
                },
              ),
              36.height,
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                mainAxisSize: MainAxisSize.min,
                children: [
                  AppFilledButton(
                    label: context.translation.reject,
                    maxWidth: true,
                    buttonColor: Colors.white54,
                    textColor: AppColor.red30,
                    showBorder: true,
                    onPressed: () async {
                      Navigator.pop(context);
                      nurseRejectBackBottomSheet(context: context);
                    },
                  ).expanded,
                  const SizedBox(
                    width: 20,
                  ),
                  AppFilledButton(
                    label: context.translation.confirm,
                    maxWidth: true,
                    loading: requestDetailProvider.isLoading,
                    buttonColor: AppColor.green70,
                    onPressed: () async {
                      if (newSignature != null) {
                        requestDetailProvider.nurseActionHelperModel = NurseActionHelperModel(workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId!, signatureNurse: nurseSignature);
                        WorkOrderDetail? data = await requestDetailProvider.nurseConfirm();
                        if (data != null) {
                          if (requestDetailProvider.currentWorkOrder!.data!.requestId != null) {
                            requestDetailProvider.updateCurrentWorkOrder(data);
                          }
                          Navigator.pop(context);
                        }
                      } else {
                        context.translation.signaturesAreRequired.showToast;
                      }
                    },
                  ).expanded,
                ],
              )
            ],
          );
        }));
  }

  static Future nurseVerifyArrivalBottomSheet({required BuildContext context}) {
    return buildBottomSheetParent(
        context: context,
        childWidget: Consumer<CMDetailProvider>(builder: (context, CMDetailProvider requestDetailProvider, child) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const SizedBox().indicatorWidget(),
              16.height,
              Align(
                alignment: AlignmentDirectional.centerStart,
                child: context.translation.confirmEngineerArrival.bottomSheetHeadingTextStyle(context),
              ),
              8.height,
              Align(
                alignment: AlignmentDirectional.centerStart,
                child: context.translation.confirmingEngineerArrivalAction.bodyText(context),
              ),
              32.height,
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                mainAxisSize: MainAxisSize.min,
                children: [
                  AppFilledButton(
                    label: context.translation.notArrived,
                    maxWidth: true,
                    buttonColor: Colors.white54,
                    textColor: AppColor.red30,
                    showBorder: true,
                    onPressed: () async {
                      Navigator.pop(context);
                      int? status = await requestDetailProvider.nurseRejectEngineerArrival(workOrderId: requestDetailProvider.currentWorkOrder?.data?.requestId ?? 0);
                      if (status == 200) {
                        requestDetailProvider.getWorkOrderById(id: requestDetailProvider.currentWorkOrder!.data!.requestId!);
                      }
                    },
                  ).expanded,
                  const SizedBox(
                    width: 20,
                  ),
                  AppFilledButton(
                    label: context.translation.arrived,
                    maxWidth: true,
                    loading: requestDetailProvider.isLoading,
                    buttonColor: AppColor.green70,
                    onPressed: () async {
                      Navigator.pop(context);
                      int? status = await requestDetailProvider.nurseConfirmEngineerArrival(workOrderId: requestDetailProvider.currentWorkOrder?.data?.requestId ?? 0);
                      if (status == 200) {
                        requestDetailProvider.getWorkOrderById(id: requestDetailProvider.currentWorkOrder!.data!.requestId!);
                      }
                    },
                  ).expanded,
                ],
              )
            ],
          );
        }));
  }

  static Future waitingForApprovalBottomSheet({required BuildContext context}) {
    return buildBottomSheetParent(
        context: context,
        isDismissible: false,
        childWidget: Consumer<CMDetailProvider>(builder: (context, CMDetailProvider requestDetailProvider, child) {
          return WillPopScope(
            onWillPop: () async {
              // Return `false` to block back navigation

              return false;
            },
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    "Waiting...".heading4(context),
                    Container(
                      padding: EdgeInsets.all(5.toScreenHeight),
                      decoration: const BoxDecoration(shape: BoxShape.circle, color: AppColor.neutral80),
                      child: const Icon(Icons.close),
                    ).onPress(() {
                      Navigator.pop(context);
                    }),
                  ],
                ),
                12.height,
                Text(
                  "Request Sent, Waiting for requester to confirm arrival",
                  style: TextStyle(
                    fontSize: 16.toScreenWidth,
                    fontWeight: FontWeight.w500,
                    fontStyle: FontStyle.normal,
                    decoration: TextDecoration.none,
                  ),
                ),
                12.height,
                "waiting".toLottieAsset(height: 100).center,
                12.height,
              ],
            ),
          );
        }));
  }

  static Future nurseVerifyAssetTransferBottomSheet({required BuildContext context, required Function(String? value) onAckhnowledgePress}) {
    bool acknowledge = false;
    Uint8List? newSignature;
    String? nurseSignature;
    return buildBottomSheetParent(
        context: context,
        childWidget: Consumer<CMDetailProvider>(builder: (context, CMDetailProvider requestDetailProvider, child) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              const SizedBox().indicatorWidget(),
              8.height,
              Align(
                alignment: AlignmentDirectional.centerStart,
                child: "Signature".bottomSheetHeadingTextStyle(context),
              ),
              10.height,
              StatefulBuilder(
                builder: (context, setState) {
                  return ESignature(
                    title: '',
                    oldSignature: '',
                    newSignature: newSignature,
                    backgroundColor: AppColor.neutral100,
                    showShadow: false,
                    onChange: (signature) {
                      if (signature.isEmpty) return;
                      setState(() {
                        newSignature = signature;
                        nurseSignature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
                      });
                    },
                    onSaved: (signature) {
                      if (signature == null || signature.isEmpty) return;
                      setState(() {
                        newSignature = signature;
                        nurseSignature = "${DateTime.now().toIso8601String()}.png|${base64Encode(signature)}";
                      });
                    },
                  );
                },
              ),
              36.height,
              AppFilledButton(
                label: context.translation.confirm,
                maxWidth: true,
                loading: requestDetailProvider.isLoading,
                buttonColor: AppColor.green70,
                onPressed: () async {
                  if (newSignature != null) {
                    Navigator.pop(context);
                    onAckhnowledgePress(nurseSignature);
                  } else {
                    context.translation.signaturesAreRequired.showToast;
                  }
                },
              )
              // Row(
              //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
              //   mainAxisSize: MainAxisSize.min,
              //   children: [
              //     // AppFilledButton(
              //     //   label: context.translation.cancel,
              //     //   maxWidth: true,
              //     //   buttonColor: AppColor.white60,
              //     //   textColor: AppColor.black10,
              //     //   showBorder: true,
              //     //   onPressed: () async {
              //     //     Navigator.pop(context);
              //     //   },
              //     // ).expanded,
              //     // const SizedBox(
              //     //   width: 20,
              //     // ),
              //     AppFilledButton(
              //       label: context.translation.confirm,
              //       maxWidth: true,
              //       loading: requestDetailProvider.isLoading,
              //       buttonColor: AppColor.green70,
              //       onPressed: () async {
              //         if (newSignature != null) {
              //           requestDetailProvider.nurseActionHelperModel = NurseActionHelperModel(workOrderId: requestDetailProvider.currentWorkOrder!.data!.requestId!, signatureNurse: nurseSignature);
              //           WorkOrderDetail? data = await requestDetailProvider.nurseConfirm();
              //           if (data != null) {
              //             if (requestDetailProvider.currentWorkOrder!.data!.requestId != null) {
              //               requestDetailProvider.updateCurrentWorkOrder(data);
              //             }
              //             Navigator.pop(context);
              //           }
              //         } else {
              //           context.translation.signaturesAreRequired.showToast;
              //         }
              //       },
              //     ).expanded,
              //   ],
              // )
            ],
          );
        }));
  }
}
