import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/all_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/generic_attachment_model.dart';
import 'package:test_sa/models/lookup.dart';
import 'package:test_sa/models/new_models/building.dart';
import 'package:test_sa/models/new_models/department.dart';
import 'package:test_sa/models/new_models/floor.dart';
import 'package:test_sa/models/new_models/task_request/task_request_model.dart';
import 'package:test_sa/modules/cm_module/utilities/service_request_utils.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.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/default_app_bar.dart';
import 'package:test_sa/new_views/common_widgets/single_item_drop_down_menu.dart';
import 'package:test_sa/providers/gas_request_providers/site_provider.dart';
import 'package:test_sa/providers/loading_list_notifier.dart';
import 'package:test_sa/providers/task_request_provider/task_job_provider.dart';
import 'package:test_sa/providers/task_request_provider/task_request_provider.dart';
import 'package:test_sa/views/app_style/sizing.dart';
import 'package:test_sa/views/widgets/date_and_time/date_picker.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';
import 'package:test_sa/views/widgets/loaders/app_loading.dart';
import 'package:test_sa/views/widgets/loaders/no_data_found.dart';
import 'package:test_sa/views/widgets/status/report/service_report_assistant_employee_menu.dart';
import 'package:test_sa/views/widgets/timer/app_timer.dart';

import '../../../../models/new_models/site.dart';
import '../../../../models/new_models/work_order_detail_model.dart';

class UpdateTaskRequest extends StatefulWidget {
  final int taskId;

  const UpdateTaskRequest({Key? key, required this.taskId}) : super(key: key);

  @override
  State<UpdateTaskRequest> createState() => _UpdateTaskRequestState();
}

class _UpdateTaskRequestState extends State<UpdateTaskRequest> {
  TaskRequestProvider? _taskProvider;
  final TextEditingController _requestedQuantityController = TextEditingController();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  List<GenericAttachmentModel> attachments = [];
  bool installationType = true;
  String comments = '';

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      assignData();
    });

    super.initState();
  }

  Future<void> assignData() async {
    _taskProvider = Provider.of<TaskRequestProvider>(context, listen: false);
    TaskData? taskModel = _taskProvider!.taskRequestModel;
    _taskProvider?.updateTaskModel(taskModel);
    if (taskModel != null) {
      attachments.addAll(taskModel.taskJobAttachments!.map((e) => GenericAttachmentModel(id:e.id,name:e.name ?? '')).toList());
      // if (taskModel.taskType?.isInstallation == true) {
      //   await _taskProvider!.getSiteData(siteId: taskModel.asset?.siteId);
      // }
    }
  }

  @override
  void dispose() {
    _requestedQuantityController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<TaskRequestProvider>(builder: (context, taskProvider, child) {
      return Scaffold(
        appBar: DefaultAppBar(
          title: context.translation.taskRequest,
          onWillPopScope: () {
            _updateTask(context: context, status: 0);
          },
        ),
        key: _scaffoldKey,
        body: taskProvider.isLoading
            ? const ALoading()
            : taskProvider.taskRequestModel != null
                ? SafeArea(
                    child: Form(
                      key: _formKey,
                      child: Stack(
                        children: [
                          SingleChildScrollView(
                            padding: EdgeInsets.all(12 * AppStyle.getScaleFactor(context)),
                            child: Column(
                              children: [
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    _timerWidget(context, true, taskProvider),
                                    8.height,
                                    if (taskProvider.taskRequestModel?.taskType?.isInstallation == true) ...[installationWidget(taskModel: taskProvider.taskRequestModel!)],
                                    if (taskProvider.taskRequestModel?.taskType?.isRecallAndAlert == true) ...[
                                      recallAlertTypeWidget(taskModel: taskProvider.taskRequestModel!),
                                    ],
                                    // if (previousComments.isNotEmpty) ...[
                                    //   'Previous Comments'.bodyText2(context).custom(color: AppColor.neutral50),
                                    //   8.height,
                                    buildPreviousComments(taskProvider: taskProvider),
                                    //   8.height,
                                    // ],
                                    AppTextFormField(
                                      initialValue: "",
                                      labelText: context.translation.technicalComment,
                                      textInputType: TextInputType.multiline,
                                      backgroundColor: AppColor.fieldBgColor(context),
                                      labelStyle: TextStyle(color: AppColor.textColor(context)),
                                      showShadow: false,
                                      alignLabelWithHint: true,
                                      onChange: (value) {
                                        comments = value;
                                        setState(() {});
                                      },
                                      onSaved: (value) {},
                                    ),
                                    20.height,
                                    AttachmentPicker(
                                      label: context.translation.attachFiles,
                                      attachment: attachments,
                                      buttonColor: AppColor.black10,
                                      onlyImages: false,
                                      buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.neutral120),
                                    ),
                                  ],
                                ).toShadowContainer(context),
                                16.height,
                                const AssistantEmployeeCard().toShadowContainer(context, paddingObject: const EdgeInsets.symmetric(horizontal: 16)),
                              ],
                            ),
                          ).paddingOnly(bottom: 85),
                          FooterActionButton.footerContainer(
                            context: context,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                              children: [
                                AppFilledButton(
                                  label: context.translation.save,
                                  buttonColor: AppColor.white60,
                                  textColor: AppColor.black10,
                                  onPressed: () => _updateTask(context: context, status: 0),
                                ).expanded,
                                12.width,
                                AppFilledButton(
                                  label: context.translation.complete,
                                  buttonColor: AppColor.primary10,
                                  onPressed: () => _updateTask(context: context, status: 1),
                                ).expanded,
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  )
                : NoDataFound(message: context.translation.noDataFound).center,
      ).handlePopScope(
          cxt: context,
          onSave: () {
            _updateTask(context: context, status: 0);
          });
    });
  }

  void _updateTask({required BuildContext context, required int status}) async {
    TaskRequestProvider taskRequestProvider = Provider.of<TaskRequestProvider>(context, listen: false);
    TaskData? taskModel = taskRequestProvider.taskRequestModel;
    taskModel?.statusValue = status;
    if (validate(model: taskModel)) {
      showDialog(context: context, barrierDismissible: false, builder: (context) => const AppLazyLoading());
      List<TaskJobAttachment> attachment = [];
      for (var item in attachments) {
        String fileName = ServiceRequestUtils.isLocalUrl(item.name??'') ? ("${item.name??''.split("/").last}|${base64Encode(File(item.name??'').readAsBytesSync())}") :item.name??'';
        attachment.add(TaskJobAttachment(id: item.id, name: fileName));
      }
      taskModel?.taskJobAttachments = attachment;
      if (taskModel?.taskTimePicker != null) {
        int durationInSecond = taskModel!.taskTimePicker!.endAt!.difference(taskModel.taskTimePicker!.startAt!).inSeconds;
        taskModel.taskJobActivityEngineerTimers?.add(
          TaskJobActivityEngineerTimer(
            id: 0,
            startDate: taskModel.taskTimePicker!.startAt!.toIso8601String(), // Handle potential null
            endDate: taskModel.taskTimePicker!.endAt?.toIso8601String(), // Handle potential null
            totalWorkingHour: ((durationInSecond) / 60 / 60),
          ),
        );
      }
      taskModel?.timerModelList?.forEach((timer) {
        int durationInSecond = timer.endAt!.difference(timer.startAt!).inSeconds;
        taskModel.taskJobActivityEngineerTimers?.add(
          TaskJobActivityEngineerTimer(
              id: 0,
              startDate: timer.startAt!.toIso8601String(),
              // Handle potential null
              endDate: timer.endAt?.toIso8601String(),
              // Handle potential null
              totalWorkingHour: ((durationInSecond) / 60 / 60),
              // comment: timer.comments,
              comment: timer.comments ?? comments),
        );
      });

// TODO need to test this when task is enabled ...
      // await taskRequestProvider.updateTaskByEngineer().then((success) {
      //   Navigator.pop(context);
      //   if (success) {
      //     if (status == 1) {
      //       AllRequestsProvider allRequestsProvider = Provider.of<AllRequestsProvider>(context, listen: false);
      //       allRequestsProvider.reset();
      //        allRequestsProvider.getAllRequests(context, typeTransaction: 6);
      //     } else {
      //        taskRequestProvider.getTaskById(id: widget.taskId, showLoading: false);
      //
      //     }
      //     Navigator.pop(context);
      //     Navigator.pop(context);
      //   }
      // });

      await taskRequestProvider.updateTaskByEngineer().whenComplete(() async {
        if (taskRequestProvider.stateCode == 200) {
          if (status == 1) {
            AllRequestsProvider allRequestsProvider = Provider.of<AllRequestsProvider>(context, listen: false);
            allRequestsProvider.reset();
            await allRequestsProvider.getAllRequests(context, typeTransaction: 6);
            Navigator.pop(context);
            Navigator.pop(context);
            Navigator.pop(context);
          } else {
            await taskRequestProvider.getTaskById(id: widget.taskId, showLoading: false);
            Navigator.pop(context);
            Navigator.pop(context);
          }
        } else {
          Navigator.pop(context);
        }
      });
    }
  }

  Widget installationWidget({required TaskData taskModel}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ADatePicker(
          label: context.translation.installationDate,
          hideShadow: true,
          backgroundColor: AppColor.fieldBgColor(context),
          date: DateTime.tryParse(taskModel.installationDate ?? ""),
          formatDateWithTime: false,
          onDatePicker: (selectedDate) {
            showTimePicker(
              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,
                );
                taskModel.installationDate = selectedDateTime.toIso8601String();
                setState(() {});
              }
            });
          },
        ),
        8.height,
        AppTextFormField(
          labelText: context.translation.serialNo,
          backgroundColor: AppColor.fieldBgColor(context),
          showShadow: false,
          labelStyle: AppTextStyles.textFieldLabelStyle,
          initialValue: taskModel.serialNo ?? '',
          textInputType: TextInputType.text,
          onChange: (value) {
            taskModel.serialNo = value;
          },
        ),
        8.height,
        SingleItemDropDownMenu<Site, SiteProvider>(
          context: context,
          title: 'Installation Site',
          initialValue: taskModel.site,
          loading: _taskProvider?.isSiteLoading,
          showAsBottomSheet: true,
          backgroundColor: AppColor.fieldBgColor(context),
          showShadow: false,
          enabled: false,
          onSelect: (value) {
            if (value == null) {
              return;
            }
            taskModel.site = value;
            taskModel.building = null;
            taskModel.floor = null;
            taskModel.department = null;
            setState(() {});
          },
        ),
        8.height,
        SingleItemDropDownMenu<Building, NullableLoadingProvider>(
          context: context,
          title: 'Installation Building',
          backgroundColor: AppColor.fieldBgColor(context),
          showAsBottomSheet: true,
          loading: _taskProvider?.isSiteLoading,
          showShadow: false,
          initialValue: taskModel.building,
          enabled: taskModel.site?.buildings?.isNotEmpty ?? false,
          staticData: taskModel.site?.buildings ?? [],
          onSelect: (value) {
            if (value == null) {
              return;
            }
            taskModel.building = value;
            taskModel.floor = null;
            taskModel.department = null;
            setState(() {});
          },
        ),
        8.height,
        SingleItemDropDownMenu<Floor, NullableLoadingProvider>(
          context: context,
          showAsBottomSheet: true,
          backgroundColor: AppColor.fieldBgColor(context),
          loading: _taskProvider?.isSiteLoading,
          showShadow: false,
          title: 'Installation Floor',
          initialValue: taskModel.floor,
          enabled: taskModel.building?.floors?.isNotEmpty ?? false,
          staticData: taskModel.building?.floors ?? [],
          onSelect: (value) {
            if (value == null) {
              return;
            }
            taskModel.floor = value;
            taskModel.department = null;
            setState(() {});
          },
        ),
        8.height,
        SingleItemDropDownMenu<Department, NullableLoadingProvider>(
          context: context,
          title: 'Installation Department',
          backgroundColor: AppColor.fieldBgColor(context),
          loading: _taskProvider?.isSiteLoading,
          showAsBottomSheet: true,
          showShadow: false,
          initialValue: taskModel.department,
          enabled: taskModel.floor?.departments?.isNotEmpty ?? false,
          staticData: taskModel.floor?.departments ?? [],
          onSelect: (value) {
            if (value == null) {
              return;
            }
            taskModel.department = value;
            taskModel.room = null;
            setState(() {});
          },
        ),
      ],
    );
  }

  Widget recallAlertTypeWidget({required TaskData taskModel}) {
    Widget userAcknowledgeWidget() {
      return Row(
        children: [
          InkWell(
            child: taskModel.isUserAcknowledge == true
                ? const Icon(
                    Icons.check_box,
                    color: AppColor.primary10,
                  )
                : const Icon(
                    Icons.check_box_outline_blank,
                    color: AppColor.neutral120,
                  ),
            onTap: () {
              setState(() {
                taskModel.isUserAcknowledge = !taskModel.isUserAcknowledge!;
              });
            },
          ),
          6.width,
          Flexible(
            child: context.translation.acknowledge.bodyText(context).custom(color: context.isDark ? AppColor.primary50 : AppColor.neutral120),
          ),
        ],
      );
    }

    if (taskModel.typeOfAlert != null) {
      switch (taskModel.typeOfAlert!.value) {
        case 1:
          return userAcknowledgeWidget();
        case 2:
          return Column(
            children: [
              SingleItemDropDownMenu<Lookup, TaskJobActionNeededProvider>(
                context: context,
                height: 56.toScreenHeight,
                title: context.translation.completedActions,
                showShadow: false,
                backgroundColor: AppColor.fieldBgColor(context),
                enabled: false,
                showAsBottomSheet: true,
                initialValue: taskModel.actionNeeded,
                onSelect: (status) {
                  //read only ...
                },
              ),
              if (taskModel.actionNeeded?.value == 1) ...[
                8.height,
                SingleItemDropDownMenu<Lookup, TaskJobImpactStatusProvider>(
                  context: context,
                  height: 56.toScreenHeight,
                  title: context.translation.impactStatus,
                  showShadow: false,
                  backgroundColor: AppColor.fieldBgColor(context),
                  showAsBottomSheet: true,
                  initialValue: taskModel.impactStatus,
                  onSelect: (status) {
                    if (status != null) {
                      taskModel.impactStatus = status;
                      setState(() {});
                    }
                  },
                )
              ],
            ],
          );

        case 3:
          return Column(
            children: [
              userAcknowledgeWidget(),
              8.height,
              SingleItemDropDownMenu<Lookup, TaskJobActionNeededProvider>(
                context: context,
                height: 56.toScreenHeight,
                title: context.translation.completedActions,
                showShadow: false,
                backgroundColor: AppColor.fieldBgColor(context),
                enabled: false,
                showAsBottomSheet: true,
                initialValue: taskModel.actionNeeded,
                onSelect: (status) {
                  //this is read only ...
                },
              ),
              8.height,
              if (taskModel.actionNeeded?.value == 1) ...[
                SingleItemDropDownMenu<Lookup, TaskJobImpactStatusProvider>(
                  context: context,
                  height: 56.toScreenHeight,
                  title: context.translation.impactStatus,
                  showShadow: false,
                  backgroundColor: AppColor.fieldBgColor(context),
                  showAsBottomSheet: true,
                  initialValue: taskModel.impactStatus,
                  onSelect: (status) {
                    if (status != null) {
                      taskModel.impactStatus = status;
                      setState(() {});
                    }
                  },
                )
              ],
            ],
          );
        default:
          return const SizedBox();
      }
    }
    return const SizedBox();
  }

  Widget _timerWidget(BuildContext context, bool isTimerEnable, TaskRequestProvider taskProvider) {
    double totalWorkingHours =
        taskProvider.taskRequestModel?.taskJobActivityEngineerTimers?.fold(0.0, (sum, item) => (sum ?? 0) + DateTime.parse(item.endDate!).difference(DateTime.parse(item.startDate!)).inSeconds) ?? 0;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        AppTimer(
          label: context.translation.timer,
          timer: taskProvider.taskRequestModel?.taskTimerModel,
          width: double.infinity,
          enabled: isTimerEnable,
          decoration: BoxDecoration(
            color: AppColor.fieldBgColor(context),
            borderRadius: BorderRadius.circular(10),
          ),
          pickerTimer: taskProvider.taskRequestModel?.taskTimePicker,
          onPick: (time) {
            taskProvider.taskRequestModel?.taskTimePicker = time;
          },
          timerProgress: (isRunning) {},
          onChange: (timer) async {
            taskProvider.updateTaskTimer(timer: timer);
            return true;
          },
        ),
        if (totalWorkingHours > 0.0) ...[
          8.height,
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              'Total Working Time:'.bodyText2(context).custom(color: AppColor.textColor(context)),
              8.width,
              Text(
                ServiceRequestUtils.formatTimerDuration(totalWorkingHours.round()),
                style: AppTextStyles.bodyText.copyWith(color: AppColor.textColor(context), fontWeight: FontWeight.w600),
              ),
            ],
          ),
        ],
        8.height,
      ],
    );
  }

  Widget buildPreviousComments({required TaskRequestProvider taskProvider}) {
    String previousComments = taskProvider.taskRequestModel?.taskJobActivityEngineerTimers?.map((e) => e.comment?.trim()).where((comment) => comment != null && comment!.isNotEmpty).join('\n') ?? '';
    if (previousComments.isNotEmpty) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          8.height,
          'Previous Comments'.bodyText2(context).custom(color: AppColor.neutral50),
          8.height,
          Container(
            constraints: BoxConstraints(
              maxHeight: 200.toScreenHeight,
            ),
            child: SingleChildScrollView(
              child: previousComments.bodyText2(context).custom(color: AppColor.neutral50),
            ),
          ).toShadowContainer(showShadow: false, context, backgroundColor: AppColor.neutral90, paddingObject: const EdgeInsets.only(left: 10, right: 20, bottom: 20, top: 10)),
          8.height,
        ],
      );
    }
    return const SizedBox();
  }
}

bool validate({TaskData? model}) {
  if (model?.taskTimerModel?.startAt == null) {
    Fluttertoast.showToast(msg: "Working Hours Required");
    return false;
  }
  if (model?.taskTimerModel?.endAt == null) {
    Fluttertoast.showToast(msg: "Please Stop The Timer");
    return false;
  }
  if (model?.assistantEmployees != null) {
    if (model?.modelAssistantEmployees?.startDate == null) {
      Fluttertoast.showToast(msg: "Please Select Assistant Employee Start Time");
      return false;
    }
    if (model?.modelAssistantEmployees?.endDate == null) {
      Fluttertoast.showToast(msg: "Please Select Assistant Employee End Time");
      return false;
    }
  }

  return true;
}

class AssistantEmployeeCard extends StatefulWidget {
  const AssistantEmployeeCard({super.key});

  @override
  State<AssistantEmployeeCard> createState() => _AssistantEmployeeCardState();
}

class _AssistantEmployeeCardState extends State<AssistantEmployeeCard> {
  bool status = false;
  final TextEditingController _workingHoursController = TextEditingController(text: '');
  bool isExpanded = false;
  TaskData? taskModel;

  @override
  void initState() {
    TaskRequestProvider taskRequestProvider = Provider.of<TaskRequestProvider>(context, listen: false);
    taskModel = taskRequestProvider.taskRequestModel;

    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose

    _workingHoursController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<TaskRequestProvider>(builder: (context, taskRequestProvider, child) {
      return Column(
        children: [
          SizedBox(
            height: 56.toScreenHeight,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                context.translation.assistantEmployee.heading6(context).custom(color: AppColor.textColor(context)),
                Icon(isExpanded ? Icons.keyboard_arrow_up_rounded : Icons.keyboard_arrow_down_rounded),
              ],
            ),
          ).onPress(() {
            setState(() {
              isExpanded = !isExpanded;
            });
          }),
          isExpanded
              ? Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    ServiceReportAssistantEmployeeMenu(
                      title: context.translation.select,
                      backgroundColor: AppColor.fieldBgColor(context),
                      initialValue: (taskModel?.assistantEmployees?.isNotEmpty ?? false) ? taskModel?.assistantEmployees?.first : null,
                      onSelect: (employee) {
                        if (employee == null) {
                          taskModel?.assistantEmployees = [];
                        } else {
                          taskModel?.assistantEmployees = [employee.copyWith(id: 0)];
                          taskModel?.modelAssistantEmployees?.user = AssignedEmployee(userId: employee.user?.id, userName: employee.user?.name);
                        }
                      },
                    ),
                    8.height,
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        ADatePicker(
                          label: context.translation.startTime,
                          hideShadow: true,
                          backgroundColor: AppColor.fieldBgColor(context),
                          date: taskModel?.modelAssistantEmployees?.startDate,
                          // from: taskModel?.d,
                          formatDateWithTime: true,
                          onDatePicker: (selectedDate) {
                            showTimePicker(
                              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 (widget.pickerFromDate != null && selectedDateTime.isBefore(widget.pickerFromDate!)) {
                                //   "Start time is before the request time.".showToast;
                                //   _pickerStartAt = null;
                                //   selectedTime = null;
                                //   return;
                                // }
                                if (selectedDateTime.isAfter(DateTime.now())) {
                                  "Start time is after than current time".showToast;
                                  selectedTime = null;
                                  return;
                                }
                                taskModel?.modelAssistantEmployees?.startDate = selectedDateTime;
                                taskRequestProvider.updateTaskModel(taskModel);
                                ServiceRequestUtils.calculateAndAssignWorkingHours(
                                    startTime: taskModel?.modelAssistantEmployees?.startDate,
                                    endTime: taskModel?.modelAssistantEmployees?.startDate,
                                    workingHoursController: _workingHoursController,
                                    updateModel: (hours) {
                                      taskModel!.modelAssistantEmployees!.workingHours = hours;
                                    });
                              }
                            });
                          },
                        ).expanded,
                        8.width,
                        ADatePicker(
                          label: context.translation.endTime,
                          hideShadow: true,
                          backgroundColor: AppColor.fieldBgColor(context),
                          date: taskModel?.modelAssistantEmployees?.endDate,
                          enable: taskModel?.modelAssistantEmployees?.startDate != null,
                          formatDateWithTime: true,
                          onDatePicker: (selectedDate) {
                            showTimePicker(
                              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 (taskModel?.modelAssistantEmployees?.startDate != null && selectedDateTime.isBefore(taskModel!.modelAssistantEmployees!.startDate!)) {
                                //   "End Date time must be greater then start date".showToast;
                                //   return;
                                // }

                                selectedDate = selectedDate.add(Duration(hours: selectedTime.hour, minutes: selectedTime.minute));
                                bool isBeforeCurrentTime = selectedDate.isBefore(DateTime.now());
                                bool isAfterStartTime = selectedDate.isAfter(taskModel!.modelAssistantEmployees!.startDate!);
                                if (!isBeforeCurrentTime) {
                                  "Please select a time before the current time.".showToast;
                                  return;
                                }
                                if (!isAfterStartTime) {
                                  "End Date time must be greater then start date".showToast;
                                  return;
                                }

                                taskModel?.modelAssistantEmployees?.endDate = selectedDate;
                                taskRequestProvider.updateTaskModel(taskModel);
                                ServiceRequestUtils.calculateAndAssignWorkingHours(
                                    startTime: taskModel?.modelAssistantEmployees?.startDate,
                                    endTime: taskModel?.modelAssistantEmployees?.endDate,
                                    workingHoursController: _workingHoursController,
                                    updateModel: (hours) {
                                      taskModel!.modelAssistantEmployees!.workingHours = hours;
                                    });
                              }
                            });
                          },
                        ).expanded,
                      ],
                    ),
                    8.height,
                    AppTextFormField(
                      labelText: context.translation.workingHours,
                      backgroundColor: AppColor.fieldBgColor(context),
                      controller: _workingHoursController,
                      suffixIcon: "clock".toSvgAsset(width: 20, color: context.isDark ? AppColor.neutral10 : null).paddingOnly(end: 16),
                      initialValue: taskModel?.modelAssistantEmployees?.workingHours != null ? taskModel!.modelAssistantEmployees!.workingHours?.toStringAsFixed(2) : '',
                      textAlign: TextAlign.center,
                      labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                      enable: false,
                      showShadow: false,
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                    8.height,
                    AppTextFormField(
                      initialValue: taskModel?.modelAssistantEmployees?.comment,
                      labelText: context.translation.comment,
                      backgroundColor: AppColor.fieldBgColor(context),
                      showShadow: false,
                      labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: AppColor.textColor(context)),
                      alignLabelWithHint: true,
                      textInputType: TextInputType.multiline,
                      onChange: (value) {
                        taskModel?.modelAssistantEmployees?.comment = value;
                      },
                      onSaved: (value) {
                        taskModel?.modelAssistantEmployees?.comment = value;
                      },
                    ),
                    16.height,
                  ],
                )
              : const SizedBox(),
        ],
      );
    });
  }
}
