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/api_routes/api_manager.dart';
import 'package:test_sa/controllers/providers/api/device_transfer_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/widget_extensions.dart';
import 'package:test_sa/helper/utils.dart';
import 'package:test_sa/models/device/asset_transfer_attachment.dart';
import 'package:test_sa/models/device/device_transfer.dart';
import 'package:test_sa/models/generic_attachment_model.dart';
import 'package:test_sa/models/new_models/assigned_employee.dart';
import 'package:test_sa/models/new_models/assistant_employee.dart';
import 'package:test_sa/models/timer_model.dart';
import 'package:test_sa/modules/cm_module/cm_request_utils.dart';
import 'package:test_sa/modules/cm_module/views/components/action_button/footer_action_button.dart';
import 'package:test_sa/modules/cm_module/views/components/bottom_sheets/service_request_bottomsheet.dart';
import 'package:test_sa/modules/cm_module/views/forms/maintenance_request/components/assistant_employee_list.dart';
import 'package:test_sa/new_views/common_widgets/app_filled_button.dart';
import 'package:test_sa/new_views/common_widgets/working_time_tile.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/date_and_time/time_picker.dart';
import 'package:test_sa/views/widgets/images/multi_image_picker.dart';
import 'package:test_sa/views/widgets/loaders/loading_manager.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 'package:test_sa/views/widgets/total_working_time_detail_bottomsheet.dart';

import '../../../extensions/text_extensions.dart';
import '../../../models/ppm/ppm.dart';
import '../../../new_views/app_style/app_color.dart';
import '../../../new_views/common_widgets/app_text_form_field.dart';
import '../../../new_views/common_widgets/default_app_bar.dart';

class UpdateDeviceTransfer extends StatefulWidget {
  final DeviceTransfer model;
  final bool isSender;

  const UpdateDeviceTransfer({Key? key, required this.model, required this.isSender}) : super(key: key);

  @override
  State<UpdateDeviceTransfer> createState() => _UpdateDeviceTransferState();
}

class _UpdateDeviceTransferState extends State<UpdateDeviceTransfer> {
  final bool _isLoading = false;

  late DeviceTransferProvider _deviceTransferProvider;
  final TextEditingController _requestedQuantityController = TextEditingController();
  final DeviceTransfer _formModel = DeviceTransfer();
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  List<TimerHistoryModel> timerList = [];
  double totalWorkingHours = 0;

  List<GenericAttachmentModel> attachments = [];

  _update({required int status}) async {
    _formKey.currentState!.save();
    if (_validateForm()) {
      _formModel.statusValue = status;
      _formModel.isSender = widget.isSender;
      _formModel.assetTransferAttachments = [];
      VisitTimers? deviceTimerPicker;
      if (_formModel.deviceTimePicker != null) {
        int durationInSecond = _formModel.deviceTimePicker!.endAt!.difference(_formModel.deviceTimePicker!.startAt!).inSeconds;
        deviceTimerPicker = VisitTimers(
          id: 0,
          startDateTime: _formModel.deviceTimePicker?.startAt?.toIso8601String(),
          endDateTime: _formModel.deviceTimePicker?.endAt?.toIso8601String(),
          workingHours: ((durationInSecond) / 60 / 60),
        );
      }
      int workingHours = _formModel.tbsTimer?.endAt!.difference(_formModel.tbsTimer!.startAt!).inSeconds ?? 0;
      if (widget.isSender) {
        if (deviceTimerPicker != null) {
          _formModel.senderVisitTimers?.add(deviceTimerPicker);
        }

        _formModel.timerModelList?.forEach((timer) {
          int durationInSecond = timer.endAt!.difference(timer.startAt!).inSeconds;
          _formModel.senderVisitTimers?.add(
            VisitTimers(
              id: 0,
              startDateTime: timer.startAt!.toIso8601String(), // Handle potential null
              endDateTime: timer.endAt?.toIso8601String(), // Handle potential null
              workingHours: ((durationInSecond) / 60 / 60),
            ),
          );
        });

        _formModel.assetTransferEngineerTimers = _formModel.senderVisitTimers;
      } else {
        if (deviceTimerPicker != null) {
          _formModel.receiverVisitTimers?.add(deviceTimerPicker);
        }

        _formModel.timerModelList?.forEach((timer) {
          int durationInSecond = timer.endAt!.difference(timer.startAt!).inSeconds;
          _formModel.receiverVisitTimers?.add(
            VisitTimers(
              id: 0,
              startDateTime: timer.startAt!.toIso8601String(), // Handle potential null
              endDateTime: timer.endAt?.toIso8601String(), // Handle potential null
              workingHours: ((durationInSecond) / 60 / 60),
            ),
          );
        });

        _formModel.assetTransferEngineerTimers = _formModel.receiverVisitTimers;
      }
      try {
        _formModel.assetTransferAttachments ??= [];
        List<GenericAttachmentModel> newAttachments = [];
        for (var item in attachments) {
          String fileName = CMRequestUtils.isLocalUrl(item.name ?? '') ? ("${item.name ?? ''.split("/").last}|${base64Encode(File(item.name ?? '').readAsBytesSync())}") : item.name ?? '';
          newAttachments.add(GenericAttachmentModel(id: item.id, documentType: item.documentType, name: fileName));
        }
        _formModel.assetTransferAttachments = [...?_formModel.assetTransferAttachments, ...newAttachments];
        _formModel.attachments = _formModel.assetTransferAttachments;
      } catch (error) {
        print(error);
      }
      if (status == 1) {
        ServiceRequestBottomSheet.nurseVerifyAssetTransferBottomSheet(
            context: context,
            onAckhnowledgePress: (signature) async {
              //TODO NEED TO CALL API HERE WITH ADDED PARAMETER FOR SIGNATURE FROM BACKEND..
              if (signature != null) {
                _formModel.nurseSignature = signature;
                await _deviceTransferProvider.updateRequest(context, model: _formModel);
              }
            });
      } else {
        await _deviceTransferProvider.updateRequest(context, model: _formModel);
      }
    }
  }

  bool _validateForm() {
    bool isTimerPickerEnable = ApiManager.instance.assetGroup?.enabledEngineerTimer ?? false;

    if (isTimerPickerEnable) {
      if (_formModel.tbsTimer?.startAt == null && _formModel.deviceTimePicker == null) {
        Fluttertoast.showToast(msg: "Working Hours Required");
        return false;
      }
      if (_formModel.deviceTimePicker == null) {
        if (_formModel.tbsTimer?.startAt == null) {
          Fluttertoast.showToast(msg: "Working Hours Required");
          return false;
        }
        if (_formModel.tbsTimer?.endAt == null) {
          Fluttertoast.showToast(msg: "Please Stop The Timer");
          return false;
        }
      }
    } else {
      if (_formModel.tbsTimer?.startAt == null) {
        Fluttertoast.showToast(msg: "Working Hours Required");
        return false;
      }
      if (_formModel.tbsTimer?.endAt == null) {
        Fluttertoast.showToast(msg: "Please Stop The Timer");
        return false;
      }
    }
// assistant employee validation
    if (_formModel.assistantEmployList?.isNotEmpty ?? false) {
      for (int i = 0; i < _formModel.assistantEmployList!.length; i++) {
        final employee = _formModel.assistantEmployList![i];
        final position = Utils.getOrdinal(i + 1);

        if (employee.employeeId == null) {
          Fluttertoast.showToast(
            msg: "Please select the $position assistant employee",
          );
          return false;
        }

        if (employee.employeeId != null) {
          if (employee.startDate == null) {
            Fluttertoast.showToast(
              msg: "Please select start time for assistant employee ${employee.employeeName}",
            );
            return false;
          }

          if (employee.endDate == null) {
            Fluttertoast.showToast(
              msg: "Please select end time for assistant employee ${employee.employeeName}",
            );
            return false;
          }
        }
      }
    }
    return true;
  }

  @override
  void initState() {
    _formModel.fromDetails(widget.model);
    attachments = widget.model.assetTransferAttachments?.map((e) => GenericAttachmentModel(id:  e.id?.toInt()??0, name: e.name!)).toList() ?? [];
    calculateWorkingTime();
    super.initState();
  }

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

  void calculateWorkingTime() {
    List<VisitTimers>  timers =[];
     if(widget.isSender){
       timers = widget.model.senderVisitTimers??[];
     } else {
       timers = widget.model.receiverVisitTimers??[];
     }
    totalWorkingHours = timers.fold<double>(0.0, (sum, item) {
      if (item.startDateTime == null || item.endDateTime == null) return sum;
      try {
        final start = DateTime.parse(item.startDateTime!);
        final end = DateTime.parse(item.endDateTime!);
        final diffInHours = end.difference(start).inSeconds / 3600.0; // convert to hours
        return sum + diffInHours;
      } catch (_) {
        return sum;
      }
    });
     print('total working time is ${totalWorkingHours}');
    timerList = timers.map((e) {
      return TimerHistoryModel(
        id: e.id,
        startTime: e.startDateTime,
        endTime: e.endDateTime,
        workingHours: e.workingHours,
      );
    }).toList();
  }

  bool isTimerRunning = false;

  @override
  Widget build(BuildContext context) {
    _deviceTransferProvider = Provider.of<DeviceTransferProvider>(context, listen: false);

    bool isTimerEnable = widget.isSender ? (!(_formModel.senderMachineStatusValue == 3)) : (!(_formModel.receiverMachineStatusValue == 3));
    return Scaffold(
      appBar: DefaultAppBar(
        title: context.translation.transferAsset,
        onWillPopScope: () {
          _update(status: 0);
        },
      ),
      key: _scaffoldKey,
      body: LoadingManager(
          isLoading: _isLoading,
          isFailedLoading: false,
          stateCode: 200,
          onRefresh: () async {},
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                SingleChildScrollView(
                  padding: EdgeInsets.all(12 * AppStyle.getScaleFactor(context)),
                  child: Column(
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          _timerWidget(context, totalWorkingHours, isTimerEnable),
                          8.height,
                          AppTextFormField(
                            initialValue: widget.isSender ? _formModel.senderComment ?? "" : _formModel.receiverComment ?? "",
                            labelText: context.translation.technicalComment,
                            hintStyle: AppTextStyles.tinyFont.copyWith(color: context.isDark?AppColor.white10:AppColor.black10),
                            labelStyle: AppTextStyles.tinyFont.copyWith(color: context.isDark?AppColor.white10:AppColor.black10),
                            textInputType: TextInputType.multiline,
                            backgroundColor: AppColor.fieldBgColor(context),
                            showShadow: false,
                            alignLabelWithHint: true,
                            onSaved: (value) {
                              widget.isSender ? _formModel.senderComment = value : _formModel.receiverComment = value;
                            },
                          ),
                          8.height,
                          AttachmentPicker(
                            label: context.translation.attachFiles,
                            showAsListView: true,
                            attachment: attachments,
                            buttonColor: AppColor.black10,
                            onlyImages: false,
                            buttonIcon: 'image-plus'.toSvgAsset(color: AppColor.primary10),
                          ),
                          8.height,
                        ],
                      ).toShadowContainer(context),
                      16.height,
                      DeviceTransferAssistantEmployeeList(
                        assetId: _formModel.assetId,
                        createdDate: _formModel.createdDate ?? '',
                        assistantEmployeeList: widget.isSender ? _formModel.assetTransferAssistantEmployeesSender : _formModel.assetTransferAssistantEmployeesReceiver,
                        cardPadding: 0,
                        onListChanged: (updatedList) {
                          setState(() {
                            _formModel.assistantEmployList = updatedList;
                          });
                        },
                      ),
                    ],
                  ),
                ).expanded,
                FooterActionButton.footerContainer(
                  context: context,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      AppFilledButton(
                        label: context.translation.save,
                        buttonColor: context.isDark?AppColor.neutral70:AppColor.white60,
                        textColor:  context.isDark?AppColor.white10:AppColor.black10,
                        onPressed: () => _update(status: 0),
                      ).expanded,
                      12.width,
                      if (!widget.isSender && _formModel.senderMachineStatusValue == 3) ...[
                        AppFilledButton(
                            label: context.translation.complete,
                            buttonColor: AppColor.primary10,
                            onPressed: () {
                              _update(status: 1);
                            }).expanded,
                      ] else if (widget.isSender) ...[
                        AppFilledButton(
                          label: context.translation.complete,
                          buttonColor: AppColor.primary10,
                          onPressed: () {
                            _update(status: 1);
                          },
                        ).expanded,
                      ],
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),

    ).handlePopScope(
        cxt: context,
        onSave: () {
          _update(status: 0);
        });
  }

  void updateTimer({TimerModel? timer}) {
    // notifyListeners();
  }

  Widget _timerWidget(BuildContext context, double totalWorkingHours, bool isTimerEnable) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        AppTimer(
          label: context.translation.workingHours,
          timer: _formModel.tbsTimer,
          pickerFromDate: DateTime.tryParse(widget.model.createdDate ?? ''),
          width: double.infinity,
          enabled: isTimerEnable,
          decoration: BoxDecoration(
            color: AppColor.fieldBgColor(context),
            borderRadius: BorderRadius.circular(10),
          ),
          pickerTimer: _formModel.deviceTimePicker,
          onPick: (time) {
            _formModel.deviceTimePicker = time;
          },
          timerProgress: (isRunning) {},
          onChange: (timer) async {
            _formModel.tbsTimer = timer;
            if (timer.startAt != null && timer.endAt != null) {
              _formModel.timerModelList = _formModel.timerModelList ?? [];
              _formModel.timerModelList!.add(timer);
            }
            return true;
          },
        ),
        if (totalWorkingHours > 0.0) ...[
          12.height,
          WorkingTimeTile(
            timerList: timerList,
            totalWorkingTime: totalWorkingHours,
          ),
          // Row(
          //   crossAxisAlignment: CrossAxisAlignment.center,
          //   mainAxisAlignment: MainAxisAlignment.start,
          //   children: [
          //     'Total Working Time:'.bodyText2(context).custom(color: AppColor.neutral120),
          //     8.width,
          //     Text(
          //       ServiceRequestUtils.formatTimerDuration(totalWorkingHours.round()),
          //       style: AppTextStyles.bodyText.copyWith(color: context.isDark?AppColor.white10: AppColor.neutral50, fontWeight: FontWeight.w600),
          //     ),
          //   ],
          // ),
        ],
      ],
    );
  }
}

class DeviceTransferAssistantEmployeeList extends StatefulWidget {
  final List<AssetTransferAssistantEmployees>? assistantEmployeeList;
  final ValueChanged<List<AssetTransferAssistantEmployees>>? onListChanged;
  final double? cardPadding;
  final dynamic assetId;
  final String createdDate;

  const DeviceTransferAssistantEmployeeList({
    super.key,
    this.assistantEmployeeList,
    this.onListChanged,
    required this.assetId,
    this.cardPadding,
    required this.createdDate,
  });

  @override
  State<DeviceTransferAssistantEmployeeList> createState() => _DeviceTransferAssistantEmployeeListState();
}

class _DeviceTransferAssistantEmployeeListState extends State<DeviceTransferAssistantEmployeeList> {
  late List<AssetTransferAssistantEmployees> _list;
  late List<TextEditingController> _controllers;

  @override
  void initState() {
    super.initState();
    _list = List<AssetTransferAssistantEmployees>.from(widget.assistantEmployeeList ?? []);
    _controllers = _list.map((e) => TextEditingController(text: e.workingHours?.toString() ?? '')).toList();
  }

  void _addNewEntry() {
    setState(() {
      _list.add(AssetTransferAssistantEmployees());
      _controllers.add(TextEditingController());
    });
    widget.onListChanged?.call(_list);
  }

  void _removeEntry(int index) {
    setState(() {
      _list.removeAt(index);
      _controllers.removeAt(index);
    });
    widget.onListChanged?.call(_list);
  }

  void _updateModel(int index, void Function(AssetTransferAssistantEmployees model) updateList, {bool updateController = false}) {
    setState(() {
      updateList(_list[index]);
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: _list.length + 1,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      padding: EdgeInsets.all(widget.cardPadding ?? 16),
      itemBuilder: (context, index) {
        if (index == _list.length) {
          return AppFilledButton(
            label: "Add Assistant Employee".addTranslation,
            maxWidth: true,
            textColor: AppColor.textColor(context),
            buttonColor: context.isDark ? AppColor.neutral60 : AppColor.white10,
            icon: Icon(Icons.add_circle, color: AppColor.blueStatus(context)),
            showIcon: true,
            onPressed: _addNewEntry,
          );
        }
        AssistantEmployees selectedEmployee = AssistantEmployees();
        AssignedEmployee? assignedUser = AssignedEmployee();
        assignedUser = AssignedEmployee(
          id: _list[index].employeeId,
          name: _list[index].employeeName,
        );
        selectedEmployee = AssistantEmployees(userId: assignedUser.id, user: assignedUser);
        return EmployeeCard(
          model: _list[index],
          assetId: widget.assetId,
          index: index,
          createdDate: widget.createdDate,
          selectedEmployee: selectedEmployee,
          onUpdate: (updateList) => _updateModel(index, updateList),
          onRemove: () => _removeEntry(index),
          workingHoursController: _controllers[index],
        );
      },
    );
  }
}

class EmployeeCard extends StatelessWidget {
  final AssetTransferAssistantEmployees model;
  final int index;
  final dynamic assetId;

  final String? createdDate;
  AssistantEmployees? selectedEmployee;
  final void Function(void Function(AssetTransferAssistantEmployees model)) onUpdate;
  final VoidCallback onRemove;
  final TextEditingController workingHoursController;

  EmployeeCard({
    super.key,
    required this.model,
    required this.assetId,
    this.selectedEmployee,
    required this.index,
    required this.onUpdate,
    this.createdDate,
    required this.onRemove,
    required this.workingHoursController,
  });

  // AssistantEmployees selectedEmployee = AssistantEmployees();
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            context.translation.assistantEmployee.bodyText(context).custom(color: AppColor.textColor(context)),
            Container(
              height: 32,
              width: 32,
              padding: const EdgeInsets.all(6),
              child: "trash".toSvgAsset(height: 20, width: 20),
            ).onPress(onRemove),
          ],
        ),
        8.height,
        Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            ServiceReportAssistantEmployeeMenu(
              title: context.translation.select,
              backgroundColor: AppColor.fieldBgColor(context),
              assetId: assetId,
              initialValue: selectedEmployee,
              onSelect: (employee) {
                if (employee != null) {
                  onUpdate((model) {
                    selectedEmployee = employee.copyWith(id: 0);
                    model.employeeId = employee.user?.id;
                    model.employeeName = employee.user?.name;
                    selectedEmployee?.user = AssignedEmployee(
                      id: employee.user?.id,
                      name: employee.user?.name,
                    );
                  });
                }
              },
            ),
            8.height,
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                ADatePicker(
                  label: context.translation.startTime,
                  hideShadow: true,
                  backgroundColor: AppColor.fieldBgColor(context),
                  date: model.startDate,
                  formatDateWithTime: true,
                  from: DateTime.tryParse(createdDate ?? ''),
                  onDatePicker: (selectedDate) {
                    showThemedTimePicker(
                      context: context,
                      initialTime: TimeOfDay.now(),
                    ).then((selectedTime) {
                      if (selectedTime != null) {
                        final selectedDateTime = DateTime(
                          selectedDate.year,
                          selectedDate.month,
                          selectedDate.day,
                          selectedTime.hour,
                          selectedTime.minute,
                        );

                        if (createdDate != null && selectedDateTime.isBefore(DateTime.tryParse(createdDate ?? '')!)) {
                          "Start time is before the request time.".showToast;
                          return;
                        }

                        if (selectedDateTime.isAfter(DateTime.now())) {
                          "Start time is after the current time".showToast;
                          return;
                        }

                        onUpdate((model) {
                          model.startDate = selectedDateTime;
                          CMRequestUtils.calculateAndAssignWorkingHours(
                            startTime: model.startDate,
                            endTime: model.endDate,
                            workingHoursController: workingHoursController,
                            updateModel: (hours) => model.workingHours = hours,
                          );
                        });
                      }
                    });
                  },
                ).expanded,
                8.width,
                ADatePicker(
                  label: context.translation.endTime,
                  hideShadow: true,
                  backgroundColor: AppColor.fieldBgColor(context),
                  date: model.endDate,
                  formatDateWithTime: true,
                  from: DateTime.tryParse(createdDate ?? ''),
                  onDatePicker: (selectedDate) {
                    showThemedTimePicker(
                      context: context,
                      initialTime: TimeOfDay.now(),
                    ).then((selectedTime) {
                      if (selectedTime != null) {
                        final endDateTime = DateTime(
                          selectedDate.year,
                          selectedDate.month,
                          selectedDate.day,
                          selectedTime.hour,
                          selectedTime.minute,
                        );

                        if (!endDateTime.isBefore(DateTime.now())) {
                          "Please select a time before the current time.".showToast;
                          return;
                        }

                        if (model.startDate == null || !endDateTime.isAfter(model.startDate!)) {
                          "End date must be after start date".showToast;
                          return;
                        }

                        onUpdate((model) {
                          model.endDate = endDateTime;
                          CMRequestUtils.calculateAndAssignWorkingHours(
                            startTime: model.startDate,
                            endTime: model.endDate,
                            workingHoursController: workingHoursController,
                            updateModel: (hours) => model.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),
              textAlign: TextAlign.center,
              enable: false,
              showShadow: false,
              labelStyle: AppTextStyles.textFieldLabelStyle,
              style: Theme.of(context).textTheme.titleMedium,
            ),
            8.height,
            AppTextFormField(
              initialValue: model.techComment,
              labelText: context.translation.technicalComment,
              backgroundColor:AppColor.fieldBgColor(context),
              showShadow: false,
              labelStyle: AppTextStyles.textFieldLabelStyle.copyWith(color: context.isDark?AppColor.white10:AppColor.black10),
              alignLabelWithHint: true,
              textInputType: TextInputType.multiline,
              onChange: (value) => onUpdate((model) => model.techComment = value),
              // onSaved: (value) => onUpdate((model) => model.technicalComment = value),
            ),
            8.height,
          ],
        )
      ],
    ).toShadowContainer(context, paddingObject: const EdgeInsets.symmetric(horizontal: 16, vertical: 12)).paddingOnly(bottom: 12);
  }
}

// class AssistantEmployeeCard extends StatefulWidget {
//   bool? isSender = false;
//   DeviceTransfer? formModel;
//
//   AssistantEmployeeCard({super.key, this.isSender, this.formModel});
//
//   @override
//   State<AssistantEmployeeCard> createState() => _AssistantEmployeeCardState();
// }
//
// class _AssistantEmployeeCardState extends State<AssistantEmployeeCard> {
//   final TextEditingController _workingHoursController = TextEditingController(text: '');
//   bool isCurrentUserIsAssistantEmp = false;
//   bool isExpanded = false;
//   List<AssetTransferAssistantEmployees> employeeList = [];
//   AssistantEmployees selectedEmployee = AssistantEmployees();

//   @override
//   void initState() {
//     WidgetsBinding.instance.addPostFrameCallback((_) {
//       getInitialData();
//     });
//     super.initState();
//   }
//
//   Future<void> getInitialData() async {
//     if (widget.isSender!) {
//       employeeList = widget.formModel!.assetTransferAssistantEmployeesSender ?? [];
//     } else {
//       employeeList = widget.formModel!.assetTransferAssistantEmployeesReceiver ?? [];
//     }
//
//     widget.formModel?.modelAssistantEmployees = employeeList.isEmpty ? AssetTransferAssistantEmployees() : employeeList[0];
//
//     AssignedEmployee? assignedUser = AssignedEmployee();
//     if (employeeList.isNotEmpty) {
//       assignedUser = AssignedEmployee(
//         id: employeeList[0].employeeId,
//         name: employeeList[0].employeeName,
//       );
//     }
//     selectedEmployee = AssistantEmployees(userId: assignedUser.id, user: assignedUser);
//   }
//
//   @override
//   void dispose() {
//     _workingHoursController.dispose();
//     super.dispose();
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return Column(
//       children: [
//         SizedBox(
//           height: 56.toScreenHeight,
//           child: Row(
//             mainAxisAlignment: MainAxisAlignment.spaceBetween,
//             children: [
//               context.translation.assistantEmployee.heading6(context).custom(color: AppColor.black10),
//               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.neutral100,
//                     assetId: widget.formModel?.assetId ?? 0,
//                     initialValue: selectedEmployee,
//                     onSelect: (employee) {
//                       if (employee == null) {
//                         widget.formModel?.assistantEmployees = [];
//                       } else {
//                         selectedEmployee = employee;
//                         widget.formModel?.assistantEmployees = [employee.copyWith(id: 0)];
//                         widget.formModel?.modelAssistantEmployees?.employeeId = employee.user?.id;
//                       }
//                     },
//                   ),
//                   8.height,
//                   Row(
//                     mainAxisSize: MainAxisSize.min,
//                     children: [
//                       ADatePicker(
//                         label: context.translation.startTime,
//                         hideShadow: true,
//                         backgroundColor: AppColor.neutral100,
//                         date: widget.formModel?.modelAssistantEmployees?.startDate,
//                         from: DateTime.tryParse(widget.formModel?.createdDate ?? ''),
//                         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 (DateTime.tryParse(widget.formModel?.createdDate ?? '') != null && selectedDateTime.isBefore(DateTime.tryParse(widget.formModel?.createdDate ?? '')!)) {
//                                 "Start time is before the request time.".showToast;
//                                 selectedTime = null;
//                                 return;
//                               }
//                               if (selectedDateTime.isAfter(DateTime.now())) {
//                                 "Start time is after than current time".showToast;
//                                 selectedTime = null;
//                                 return;
//                               }
//                               widget.formModel?.modelAssistantEmployees?.startDate = selectedDateTime;
//                               ServiceRequestUtils.calculateAndAssignWorkingHours(
//                                   startTime: widget.formModel?.modelAssistantEmployees?.startDate,
//                                   endTime: widget.formModel?.modelAssistantEmployees?.endDate,
//                                   workingHoursController: _workingHoursController,
//                                   updateModel: (hours) {
//                                     widget.formModel?.modelAssistantEmployees?.workingHours = hours;
//                                   });
//                               setState(() {});
//                             }
//                           });
//                         },
//                       ).expanded,
//                       8.width,
//                       ADatePicker(
//                         label: context.translation.endTime,
//                         hideShadow: true,
//                         backgroundColor: AppColor.neutral100,
//                         date: widget.formModel?.modelAssistantEmployees?.endDate,
//                         formatDateWithTime: true,
//                         onDatePicker: (selectedDate) {
//                           showTimePicker(
//                             context: context,
//                             initialTime: TimeOfDay.now(),
//                           ).then((selectedTime) {
//                             if (selectedTime != null) {
//                               DateTime selectedDateTime = DateTime(
//                                 selectedDate.year,
//                                 selectedDate.month,
//                                 selectedDate.day,
//                                 selectedTime.hour,
//                                 selectedTime.minute,
//                               );
//                               if (widget.formModel?.modelAssistantEmployees?.startDate != null && selectedDateTime.isBefore(widget.formModel!.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(widget.formModel!.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;
//                               }
//
//
//
//
//                               widget.formModel?.modelAssistantEmployees?.endDate = selectedDateTime;
//                               ServiceRequestUtils.calculateAndAssignWorkingHours(
//                                   startTime: widget.formModel?.modelAssistantEmployees?.startDate,
//                                   endTime: widget.formModel?.modelAssistantEmployees?.endDate,
//                                   workingHoursController: _workingHoursController,
//                                   updateModel: (hours) {
//                                     widget.formModel?.modelAssistantEmployees?.workingHours = hours;
//                                   });
//                               setState(() {});
//                             }
//                           });
//                         },
//                       ).expanded,
//                     ],
//                   ),
//                   8.height,
//                   AppTextFormField(
//                     labelText: context.translation.workingHours,
//                     backgroundColor: AppColor.neutral80,
//                     controller: _workingHoursController,
//                     suffixIcon: "clock".toSvgAsset(width: 20, color: context.isDark ? AppColor.neutral10 : null).paddingOnly(end: 16),
//                     initialValue: widget.formModel?.modelAssistantEmployees?.workingHours != null ? widget.formModel?.modelAssistantEmployees?.workingHours.toString() : '',
//                     textAlign: TextAlign.center,
//                     labelStyle: AppTextStyles.textFieldLabelStyle,
//                     enable: false,
//                     showShadow: false,
//                     style: Theme.of(context).textTheme.titleMedium,
//                   ),
//                   8.height,
//                   AppTextFormField(
//                     initialValue: widget.formModel?.modelAssistantEmployees?.techComment,
//                     labelText: context.translation.technicalComment,
//                     backgroundColor: AppColor.neutral100,
//                     showShadow: false,
//                     labelStyle: AppTextStyles.textFieldLabelStyle,
//                     alignLabelWithHint: true,
//                     textInputType: TextInputType.multiline,
//                     onChange: (value) {
//                       widget.formModel?.modelAssistantEmployees?.techComment = value;
//                     },
//                     onSaved: (value) {
//                       widget.formModel?.modelAssistantEmployees?.techComment = value;
//                     },
//                   ),
//                   16.height,
//                 ],
//               )
//             : const SizedBox(),
//       ],
//     );
//   }
// }
