import 'package:easy_localization/src/public_ext.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:lottie/lottie.dart';
import 'package:mohem_flutter_app/api/worklist/worklist_api_client.dart';
import 'package:mohem_flutter_app/app_state/app_state.dart';
import 'package:mohem_flutter_app/classes/colors.dart';
import 'package:mohem_flutter_app/classes/utils.dart';
import 'package:mohem_flutter_app/extensions/int_extensions.dart';
import 'package:mohem_flutter_app/extensions/string_extensions.dart';
import 'package:mohem_flutter_app/extensions/widget_extensions.dart';
import 'package:mohem_flutter_app/generated/locale_keys.g.dart';
import 'package:mohem_flutter_app/models/generic_response_model.dart';
import 'package:mohem_flutter_app/models/get_absence_collection_notification_body_list_model.dart';
import 'package:mohem_flutter_app/models/get_action_history_list_model.dart';
import 'package:mohem_flutter_app/models/get_attachement_list_model.dart';
import 'package:mohem_flutter_app/models/get_item_creation_ntf_body_list_model.dart';
import 'package:mohem_flutter_app/models/get_mo_notification_body_list_model.dart';
import 'package:mohem_flutter_app/models/get_notification_buttons_list_model.dart';
import 'package:mohem_flutter_app/models/get_po_notification_body_list_model.dart';
import 'package:mohem_flutter_app/models/get_pr_notification_body_list_model.dart';
import 'package:mohem_flutter_app/models/get_stamp_ms_notification_body_list_model.dart';
import 'package:mohem_flutter_app/models/get_stamp_ns_notification_body_list_model.dart';
import 'package:mohem_flutter_app/models/member_information_list_model.dart';
import 'package:mohem_flutter_app/models/notification_get_respond_attributes_list_model.dart';
import 'package:mohem_flutter_app/models/worklist/GetRFCEmployeeList.dart';
import 'package:mohem_flutter_app/models/worklist/hr/eit_otification_body_model.dart';
import 'package:mohem_flutter_app/models/worklist/hr/get_basic_det_ntf_body_list_model.dart';
import 'package:mohem_flutter_app/models/worklist/hr/get_contact_notification_body_list_model.dart';
import 'package:mohem_flutter_app/models/worklist/hr/get_phones_notification_body_list_model.dart';
import 'package:mohem_flutter_app/models/worklist_response_model.dart';
import 'package:mohem_flutter_app/ui/my_attendance/dynamic_screens/dynamic_listview_screen.dart';
import 'package:mohem_flutter_app/ui/work_list/sheets/delegate_sheet.dart';
import 'package:mohem_flutter_app/ui/work_list/sheets/selected_item_sheet.dart';
import 'package:mohem_flutter_app/ui/work_list/sheets/update_continue_sheet.dart';
import 'package:mohem_flutter_app/ui/work_list/worklist_fragments/actions_fragment.dart';
import 'package:mohem_flutter_app/ui/work_list/worklist_fragments/attachments_fragment.dart';
import 'package:mohem_flutter_app/ui/work_list/worklist_fragments/detail_fragment.dart';
import 'package:mohem_flutter_app/ui/work_list/worklist_fragments/info_fragments.dart';
import 'package:mohem_flutter_app/ui/work_list/worklist_fragments/request_fragment.dart';
import 'package:mohem_flutter_app/widgets/app_bar_widget.dart';
import 'package:mohem_flutter_app/widgets/bottom_sheet.dart';
import 'package:mohem_flutter_app/widgets/button/default_button.dart';
import 'package:mohem_flutter_app/widgets/dialogs/accept_reject_input_dialog.dart';
import 'package:mohem_flutter_app/widgets/dialogs/confirm_dialog.dart';

class WorkListDetailScreen extends StatefulWidget {
  WorkListDetailScreen({Key? key}) : super(key: key);

  @override
  _WorkListDetailScreenState createState() {
    return _WorkListDetailScreenState();
  }
}

class _WorkListDetailScreenState extends State<WorkListDetailScreen> {
  int tabIndex = 0;
  PageController controller = PageController();
  bool showFabOptions = false;

  WorkListResponseModel? workListData;
  MemberInformationListModel? memberInformationListModel;
  List<GetNotificationButtonsList> notificationButtonsList = [];
  List<GetActionHistoryList> actionHistoryList = [];
  List<GetAttachementList> getAttachmentList = [];
  List<GetStampMsNotificationBodyList> getStampMsNotifications = [];
  List<GetStampNsNotificationBodyList> getStampNsNotifications = [];
  List<GetMoNotificationBodyList> getMoNotificationBodyList = [];
  List<NotificationGetRespondAttributesList> getNotificationRespondAttributes = [];
  NotificationGetRespondAttributesList? notificationNoteInput;

  List<GetRFCEmployeeList> getRFCEmployeeList = [];

  //HR Details Screen Requests
  List<GetEitCollectionNotificationBodyList>? getEitCollectionNotificationBodyList = [];
  List<GetPhonesNotificationBodyList>? getPhonesNotificationBodyList = [];
  List<GetBasicDetNtfBodyList>? getBasicDetNtfBodyList = [];
  List<GetAbsenceCollectionNotificationBodyList>? getAbsenceCollectionNotificationBodyList = [];
  GetContactNotificationBodyList? getContactNotificationBodyList;

  GenericResponseModel? getBasicNTFBody;
  GenericResponseModel? getICBody;
  GenericResponseModel? subordinatesLeavesModel;
  GetPoNotificationBodyList? getPoNotificationBody;
  GetPrNotificationBodyList? getPrNotificationBody;
  GetItemCreationNtfBodyList? getItemCreationNtfBody;

  bool isCloseAvailable = false;
  bool isApproveAvailable = false;
  bool isRejectAvailable = false;

  bool isAttachmentLoaded = false;
  bool isActionHistoryLoaded = false;

  @override
  void initState() {
    super.initState();
  }

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

  void getData() async {
    // try {
    //   Utils.showLoading(context);
    if (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") {
      getUserInformation();
    }

    notificationGetRespondAttributes();
    getNotificationButtons();
    getAttachments();
    getActionHistory();

    if (workListData!.iTEMTYPE == "HRSSA") {
      if (workListData!.rEQUESTTYPE == "EIT") {
        getEitNotificationBody();
      } else if (workListData!.rEQUESTTYPE == "PHONE_NUMBERS") {
        getPhonesNotificationBody();
      } else if (workListData!.rEQUESTTYPE == "BASIC_DETAILS") {
        getBasicDetNtfBody();
      } else if (workListData!.rEQUESTTYPE == "ABSENCE") {
        getAbsenceNotificationBody();
      } else if (workListData!.rEQUESTTYPE == "CONTACT") {
        getContactNotificationBody();
      }
      // getBasicNTFBody = await WorkListApiClient().getBasicDetNTFBody(workListData!.nOTIFICATIONID!, -999);
      // getAbsenceCollectionNotifications = await WorkListApiClient().getAbsenceNotificationBody(workListData!.nOTIFICATIONID!, -999);
      // subordinatesLeavesModel = await WorkListApiClient().getSubordinatesLeaves("", "");
    }
    if (workListData!.iTEMTYPE == "STAMP") {
      getStampNotificationBody();
    }
    if (workListData!.iTEMTYPE == "INVMOA") {
      getMoNotificationBody();
    }
    if (workListData!.iTEMTYPE == "INVITEM") {
      getItemCreationNtf();
    }
    if (workListData!.iTEMTYPE == "POAPPRV") {
      getPoNotification();
    }
    if (workListData!.iTEMTYPE == "REQAPPRV") {
      getPRNotification();
    }

    controller.jumpToPage(0);

    // List dataToFetch = await Future.wait([
    //
    //   WorkListApiClient().getActionHistory(workListData!.nOTIFICATIONID!),
    //   WorkListApiClient().getAttachments(workListData!.nOTIFICATIONID!),
    // ]);
    //
    // notificationButtonsList = dataToFetch[0];
    // actionHistoryList = dataToFetch[1];
    // getAttachmentList = dataToFetch[2];

    // if (notificationButtonsList.isNotEmpty) {
    //   isCloseAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "CLOSE");
    //   isApproveAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "APPROVED");
    //   isRejectAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "REJECTED");
    // }
    //   Utils.hideLoading(context);
    //   setState(() {});
    // } catch (ex) {
    //   Utils.hideLoading(context);
    //   Utils.handleException(ex, context, null);
    //   setState(() {});
    // }
  }

  List<Future> futureRequest = [];
  List<Object> futureObject = [];

  int apiCallCount = 0;

  void getDataFromState() {
    if (workListData == null) {
      workListData = AppState().workList![AppState().workListIndex!]; // ModalRoute.of(context)!.settings.arguments as WorkListResponseModel;
      getData();
    }
  }

  @override
  Widget build(BuildContext context) {
    getDataFromState();

    return Scaffold(
      appBar: AppBarWidget(context, title: LocaleKeys.details.tr()),
      backgroundColor: Colors.white,
      body: Stack(
        children: [
          Column(
            children: [
              Container(
                padding: const EdgeInsets.only(left: 21, right: 21, top: 16, bottom: 16),
                decoration: const BoxDecoration(
                  borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(25),
                    bottomRight: Radius.circular(25),
                  ),
                  gradient: LinearGradient(
                    transform: GradientRotation(.83),
                    begin: Alignment.topRight,
                    end: Alignment.bottomLeft,
                    colors: [
                      MyColors.gradiantEndColor,
                      MyColors.gradiantStartColor,
                    ],
                  ),
                ),
                child: Row(
                  children: [
                    myTab(LocaleKeys.info.tr(), 0),
                    (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP") ? myTab(LocaleKeys.details.tr(), 1) : myTab(LocaleKeys.request.tr(), 1),
                    myTab(LocaleKeys.actions.tr(), 2),
                    myTab(LocaleKeys.attachments.tr(), 3),
                  ],
                ),
              ),
              if ((workListData?.sUBJECT ?? "").isNotEmpty) workListData!.sUBJECT!.toText14().paddingOnly(top: 20, right: 21, left: 21),
              PageView(
                controller: controller,
                onPageChanged: (pageIndex) {
                  setState(() {
                    tabIndex = pageIndex;
                  });
                },
                children: [
                  InfoFragment(
                    poHeaderList: getPoNotificationBody?.pOHeader ?? [],
                    workListData: workListData,
                    itemCreationHeader: getItemCreationNtfBody?.itemCreationHeader ?? [],
                    getStampMsNotifications: getStampMsNotifications,
                    getStampNsNotifications: getStampNsNotifications,
                    getEitCollectionNotificationBodyList: getEitCollectionNotificationBodyList,
                    getPhonesNotificationBodyList: getPhonesNotificationBodyList,
                    getBasicDetNtfBodyList: getBasicDetNtfBodyList,
                    getAbsenceCollectionNotificationBodyList: getAbsenceCollectionNotificationBodyList,
                    getContactNotificationBodyList: getContactNotificationBodyList,
                    getPrNotificationBodyList: getPrNotificationBody,
                  ),
                  (workListData!.iTEMTYPE == "HRSSA" || workListData!.iTEMTYPE == "STAMP")
                      ? DetailFragment(workListData, memberInformationListModel)
                      : RequestFragment(
                          moNotificationBodyList: getMoNotificationBodyList,
                          poLinesList: getPoNotificationBody?.pOLines ?? [],
                          itemCreationLines: getItemCreationNtfBody?.itemCreationLines ?? [],
                          prLinesList: getPrNotificationBody?.pRLines ?? [],
                        ),
                  isActionHistoryLoaded
                      ? actionHistoryList.isEmpty
                          ? Utils.getNoDataWidget(context)
                          : ActionsFragment(
                              workListData!.nOTIFICATIONID,
                              actionHistoryList,
                              voidCallback: reloadWorkList,
                            )
                      : showLoadingAnimation(),
                  isAttachmentLoaded
                      ? getAttachmentList.isEmpty
                          ? Utils.getNoDataWidget(context)
                          : AttachmentsFragment(getAttachmentList)
                      : showLoadingAnimation(),
                ],
              ).expanded,
              if (isApproveAvailable || isRejectAvailable || isCloseAvailable)
                Container(
                  padding: const EdgeInsets.only(top: 14, bottom: 14, left: 21, right: 21),
                  decoration: const BoxDecoration(
                    color: Colors.white,
                    border: Border(
                      top: BorderSide(color: MyColors.lightGreyEFColor, width: 1.0),
                    ),
                  ),
                  child: Row(
                    children: [
                      if (isRejectAvailable)
                        DefaultButton(
                          LocaleKeys.reject.tr(),
                          () => performAction("REJECTED"),
                          colors: const [Color(0xffE47A7E), Color(0xffDE6D71)],
                        ).expanded,
                      if (isApproveAvailable && isRejectAvailable) 8.width,
                      if (isApproveAvailable)
                        DefaultButton(
                          LocaleKeys.approve.tr(),
                          () => performAction("APPROVED"),
                          colors: const [Color(0xff28C884), Color(0xff1BB271)],
                        ).expanded,
                      if (isCloseAvailable)
                        DefaultButton(
                          LocaleKeys.ok.tr(),
                          () => performAction("CLOSE"),
                          colors: const [Color(0xff32D892), Color(0xff1AB170)],
                        ).expanded,
                      8.width,
                      Container(
                        height: 43,
                        width: 43,
                        decoration: const BoxDecoration(
                          shape: BoxShape.circle,
                          color: MyColors.lightGreyE6Color,
                        ),
                        child: Icon(showFabOptions ? Icons.more_vert_rounded : Icons.more_horiz_rounded, color: MyColors.darkIconColor),
                      ).onPress(() {
                        setState(() {
                          showFabOptions = true;
                        });
                      })
                    ],
                  ),
                )
            ],
          ),
          IgnorePointer(
            ignoring: !showFabOptions,
            child: AnimatedOpacity(
              opacity: showFabOptions ? 1 : 0,
              duration: const Duration(milliseconds: 250),
              child: Container(
                padding: const EdgeInsets.only(left: 21, right: 21, bottom: 75 - 12),
                width: double.infinity,
                height: double.infinity,
                color: Colors.white.withOpacity(.67),
                alignment: Alignment.bottomRight,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    myFab(LocaleKeys.skip.tr(), "assets/images/skip.svg").onPress(() {
                      if (AppState().workList!.length - 1 > AppState().workListIndex!) {
                        AppState().setWorkListIndex = AppState().workListIndex! + 1;
                        workListData = null;
                        showFabOptions = false;
                        tabIndex = 0;
                        getDataFromState();
                      } else if (AppState().workList!.length - 1 == AppState().workListIndex!) {
                        Navigator.pop(context);
                      }
                    }),
                    12.height,
                    ...viewApiButtonsList(notificationButtonsList),
                  ],
                ),
              ),
            ).onPress(() {
              setState(() {
                showFabOptions = false;
              });
            }),
          ),
        ],
      ),
      floatingActionButton: (!isApproveAvailable && !isRejectAvailable && !isCloseAvailable)
          ? Container(
              height: 43,
              width: 43,
              decoration: const BoxDecoration(
                shape: BoxShape.circle,
                color: MyColors.lightGreyE6Color,
              ),
              child: Icon(showFabOptions ? Icons.more_vert_rounded : Icons.more_horiz_rounded, color: MyColors.darkIconColor),
            ).onPress(() {
              setState(() {
                showFabOptions = true;
              });
            })
          : null,
    );
  }

  List<Widget> viewApiButtonsList(List<GetNotificationButtonsList> notificationButtonsList) {
    List<Widget> fabs = [];
    for (int i = 0; i < notificationButtonsList.length; i++) {
      if (notificationButtonsList[i].bUTTONACTION! == "REJECTED" || notificationButtonsList[i].bUTTONACTION! == "APPROVED" || notificationButtonsList[i].bUTTONACTION! == "CLOSE") {
        continue;
      }
      fabs.add(myFab(
        notificationButtonsList[i].bUTTONLABEL!,
        getActionImage(notificationButtonsList[i].bUTTONACTION!),
        isIconAsset: true,
      ).paddingOnly(bottom: 12).onPress(() => handleFabAction(notificationButtonsList[i])));
    }
    return fabs;
  }

  String getActionImage(String action) {
    String returnActionImage = "";

    switch (action) {
      case "DELEGATE":
        returnActionImage = "assets/images/delegate.svg";
        break;
      case "REQUEST_INFO":
        returnActionImage = "assets/images/request_info.svg";
        break;
      case "RFC":
        returnActionImage = "assets/images/worklist/return.svg";
        break;
      case "UPDATE_ACTION":
        returnActionImage = "assets/images/worklist/update_action.svg";
        break;
      case "APPROVE_AND_FORWARD":
        returnActionImage = "assets/images/worklist/approve_and_forward.svg";
        break;
      case "FORWARD":
        returnActionImage = "assets/images/worklist/forward.svg";
        break;
      default:
        returnActionImage = "assets/images/request_info.svg";
        break;
    }

    return returnActionImage;
  }

  void handleFabAction(GetNotificationButtonsList notificationButton) {
    print("notificationButton:${notificationButton.bUTTONACTION}");
    switch (notificationButton.bUTTONACTION) {
      case "DELEGATE":
        showMyBottomSheet(context,
            callBackFunc: reloadWorkList,
            child: DelegateSheet(
              title: LocaleKeys.delegate.tr(),
              apiMode: notificationButton.bUTTONACTION!,
              notificationID: workListData!.nOTIFICATIONID,
              actionHistoryList: actionHistoryList,
              callBackFunc: reloadWorkList,
            ));
        break;
      case "REQUEST_INFO":
        // do something else
        showMyBottomSheet(context,
            callBackFunc: reloadWorkList,
            child: DelegateSheet(
              title: LocaleKeys.request_info.tr(),
              apiMode: "REQUEST_INFO",
              notificationID: workListData!.nOTIFICATIONID,
              actionHistoryList: actionHistoryList,
              callBackFunc: reloadWorkList,
            ));
        break;
      case "TRANSFER_INFO":
        // do something else
        showMyBottomSheet(context,
            callBackFunc: reloadWorkList,
            child: DelegateSheet(
              title: notificationButton.bUTTONLABEL!,
              apiMode: notificationButton.bUTTONACTION!,
              notificationID: workListData!.nOTIFICATIONID,
              actionHistoryList: actionHistoryList,
              callBackFunc: reloadWorkList,
            ));
        break;
      case "ANSWER_INFO":
        performAction(notificationButton.bUTTONACTION!, title: notificationButton.bUTTONLABEL);
        break;
      case "RFC":
        getRFCEmployeeListFunc();
        break;
      case "APPROVE":
        performAction(notificationButton.bUTTONACTION!);
        break;
      case "UPDATE_ACTION":
        showMyBottomSheet(
          context,
          callBackFunc: reloadWorkList,
          child: UpdateContinueSheet(
              workListData: workListData,
              getEitCollectionNotificationBodyList: getEitCollectionNotificationBodyList,
              dynamicParams: DynamicListViewParams(workListData!.sUBJECT!, workListData!.fUNCTIONNAME!,
                  isUpdate: true, collectionNotificationList: getEitCollectionNotificationBodyList![0].collectionNotification)),
        );
        break;
      case "APPROVE_AND_FORWARD":
        showMyBottomSheet(context,
            callBackFunc: reloadWorkList,
            child: DelegateSheet(
              title: "Approve and Forward",
              apiMode: notificationButton.bUTTONACTION!,
              notificationID: workListData!.nOTIFICATIONID,
              actionHistoryList: actionHistoryList,
              callBackFunc: reloadWorkList,
            ));
        break;
      case "FORWARD":
        showMyBottomSheet(context,
            callBackFunc: reloadWorkList,
            child: DelegateSheet(
              title: "Forward",
              apiMode: notificationButton.bUTTONACTION!,
              notificationID: workListData!.nOTIFICATIONID,
              actionHistoryList: actionHistoryList,
              callBackFunc: reloadWorkList,
            ));
        break;
      case "REJECT":
        performAction(notificationButton.bUTTONACTION!);
        break;
      case "RETURNED":
        Navigator.pop(context);
        break;
    }
    setState(() {
      showFabOptions = false;
    });
  }

  void getRFCEmployeeListFunc() async {
    try {
      Utils.showLoading(context);
      getRFCEmployeeList = await WorkListApiClient().getRFCEmployeeeList(workListData!.nOTIFICATIONID!);
      Utils.hideLoading(context);
      actionHistoryList.last.sEQUENCE = getRFCEmployeeList[0].sEQ;
      showMyBottomSheet(context,
          callBackFunc: reloadWorkList,
          child: SelectedItemSheet(
            "Comment",
            apiMode: "RFC",
            actionHistoryList: actionHistoryList.last,
            notificationID: workListData!.nOTIFICATIONID,
            isITGRequest: false,
          ));
      setState(() {});
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  Future<void> performNetworkCall(BuildContext context, {String? email, String? userId}) async {
    showDialog(
      context: context,
      builder: (cxt) => ConfirmDialog(
        message: LocaleKeys.wantToReject.tr(),
        okTitle: LocaleKeys.reject.tr(),
        onTap: () async {
          Navigator.pop(cxt);
          Utils.showLoading(context);
          try {
            await WorkListApiClient().submitComment(comment: "", email: email, userId: userId, notificationId: workListData!.nOTIFICATIONID, apiMode: "REJECT");
            Utils.hideLoading(context);
            Navigator.pop(context, "delegate_reload");
          } catch (ex) {
            Utils.hideLoading(context);
            Utils.handleException(ex, context, null);
          }
        },
      ),
    );
  }

  Widget myTab(String title, int index) {
    bool isSelected = (index == tabIndex);
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        title.toText12(color: isSelected ? Colors.white : Colors.white.withOpacity(.74), isCenter: true),
        4.height,
        Container(
          height: 8,
          width: 8,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: isSelected ? Colors.white : Colors.transparent,
          ),
        ).onPress(() {
          setState(() {
            showFabOptions = true;
          });
        })
      ],
    ).onPress(() {
      controller.jumpToPage(index);
    }).expanded;
  }

  Widget myFab(String title, String icon, {bool isIconAsset = true}) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        title.toText16(),
        14.width,
        Container(
          height: 43,
          width: 43,
          padding: const EdgeInsets.all(12),
          decoration: const BoxDecoration(
            shape: BoxShape.circle,
            gradient: LinearGradient(
              transform: GradientRotation(.46),
              begin: Alignment.topRight,
              end: Alignment.bottomLeft,
              colors: [
                MyColors.gradiantEndColor,
                MyColors.gradiantStartColor,
              ],
            ),
          ),
          child: isIconAsset
              ? SvgPicture.asset(icon)
              : Image.memory(
                  Utils.dataFromBase64String(icon),
                  fit: BoxFit.cover,
                ),
        )
      ],
    );
  }

  void performAction(String actionMode, {String? title}) {
    print(actionMode);
    showDialog(
      context: context,
      builder: (cxt) => AcceptRejectInputDialog(
        message: title != null ? null : LocaleKeys.requestedItems.tr(),
        title: title,
        notificationGetRespond: notificationNoteInput,
        actionMode: actionMode,
        onTap: (note) {
          Map<String, dynamic> payload = {
            "P_ACTION_MODE": actionMode,
            "P_APPROVER_INDEX": null,
            "P_COMMENTS": note,
            "P_FORWARD_TO_USER_NAME": "",
            "P_NOTIFICATION_ID": workListData!.nOTIFICATIONID,
            "RespondAttributeList": [
              if (notificationNoteInput != null)
                {
                  "ATTRIBUTE_NAME": notificationNoteInput!.attributeName,
                  if (notificationNoteInput!.attributeType == "number") "ATTRIBUTE_NUMBER_VALUE": note else if (notificationNoteInput!.attributeType == "VARCHAR2") "ATTRIBUTE_TEXT_VALUE": note
                }
            ],
          };
          if (actionMode == "APPROVED" || actionMode == "APPROVE" || actionMode == "CLOSE" || actionMode == "ANSWER_INFO" || actionMode == "RFC") {
            performNotificationAction(payload);
          } else if (note.isNotEmpty && (actionMode != "APPROVED" || actionMode != "APPROVE")) {
            performNotificationAction(payload);
          } else {
            Utils.showToast(LocaleKeys.pleaseEnterComments.tr());
          }
        },
      ),
    );
  }

  void performNotificationAction(Map<String, dynamic> payload) async {
    try {
      Utils.showLoading(context);
      GenericResponseModel model = await WorkListApiClient().postNotificationActions(payload);
      Utils.hideLoading(context);
      Utils.showToast(LocaleKeys.yourChangeHasBeenSavedSuccessfully.tr());
      AppState().workList!.removeAt(AppState().workListIndex!);
      if (AppState().workList!.isEmpty) {
        Navigator.pop(context, "delegate_reload");
      } else {
        if (AppState().workList!.length <= AppState().workListIndex!) {
          Navigator.pop(context, "delegate_reload");
        } else {
          workListData = null;
          getDataFromState();
        }
      }
    } catch (ex) {
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void reloadWorkList() {
    AppState().workList!.removeAt(AppState().workListIndex!);
    if (AppState().workList!.isEmpty) {
      Navigator.pop(context, "delegate_reload");
    } else {
      if (AppState().workList!.length <= AppState().workListIndex!) {
        Navigator.pop(context, "delegate_reload");
      } else {
        workListData = null;
        getDataFromState();
      }
    }
  }

  void getEitNotificationBody() async {
    try {
      if (apiCallCount == 0) Utils.showLoading(context);
      apiCallCount++;
      getEitCollectionNotificationBodyList = await WorkListApiClient().GetEitNotificationBody(workListData!.nOTIFICATIONID);
      apiCallCount--;
      if (apiCallCount == 0) {
        Utils.hideLoading(context);
        setState(() {});
      }
    } catch (ex) {
      apiCallCount--;
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getUserInformation() async {
    try {
      if (apiCallCount == 0) Utils.showLoading(context);
      apiCallCount++;
      memberInformationListModel = await WorkListApiClient().getUserInformation(-999, workListData!.sELECTEDEMPLOYEENUMBER!);
      apiCallCount--;
      if (apiCallCount == 0) {
        Utils.hideLoading(context);
        setState(() {});
      }
    } catch (ex) {
      apiCallCount--;
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getPhonesNotificationBody() async {
    try {
      if (apiCallCount == 0) Utils.showLoading(context);
      apiCallCount++;
      getPhonesNotificationBodyList = await WorkListApiClient().getPhonesNotificationBodyList(workListData!.nOTIFICATIONID);
      apiCallCount--;
      if (apiCallCount == 0) {
        Utils.hideLoading(context);
        setState(() {});
      }
    } catch (ex) {
      apiCallCount--;
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getBasicDetNtfBody() async {
    try {
      if (apiCallCount == 0) Utils.showLoading(context);
      apiCallCount++;
      getBasicDetNtfBodyList = await WorkListApiClient().getBasicDetNtfBodyList(workListData!.nOTIFICATIONID);
      apiCallCount--;
      if (apiCallCount == 0) {
        Utils.hideLoading(context);
        setState(() {});
      }
    } catch (ex) {
      apiCallCount--;
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getAbsenceNotificationBody() async {
    try {
      if (apiCallCount == 0) Utils.showLoading(context);
      apiCallCount++;
      getAbsenceCollectionNotificationBodyList = await WorkListApiClient().getAbsenceNotificationBody(workListData!.nOTIFICATIONID);
      apiCallCount--;
      if (apiCallCount == 0) {
        Utils.hideLoading(context);
        setState(() {});
      }
    } catch (ex) {
      apiCallCount--;
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getContactNotificationBody() async {
    try {
      if (apiCallCount == 0) Utils.showLoading(context);
      apiCallCount++;
      getContactNotificationBodyList = await WorkListApiClient().getContactNotificationBodyList(workListData!.nOTIFICATIONID);
      apiCallCount--;
      if (apiCallCount == 0) {
        Utils.hideLoading(context);
        setState(() {});
      }
    } catch (ex) {
      apiCallCount--;
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getStampNotificationBody() async {
    try {
      if (apiCallCount == 0) Utils.showLoading(context);
      apiCallCount++;
      if (workListData!.rEQUESTTYPE == "STAMP_MS") {
        getStampMsNotifications = await WorkListApiClient().getStampMsNotificationBody(workListData!.nOTIFICATIONID!, -999);
      } else {
        getStampNsNotifications = await WorkListApiClient().getStampNsNotificationBody(workListData!.nOTIFICATIONID!, -999);
      }
      apiCallCount--;
      if (apiCallCount == 0) {
        Utils.hideLoading(context);
        setState(() {});
      }
    } catch (ex) {
      apiCallCount--;
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getMoNotificationBody() async {
    try {
      if (apiCallCount == 0) Utils.showLoading(context);
      apiCallCount++;
      getMoNotificationBodyList = await WorkListApiClient().getMoNotificationBody(workListData!.nOTIFICATIONID!, -999);
      apiCallCount--;
      if (apiCallCount == 0) {
        Utils.hideLoading(context);
        setState(() {});
      }
    } catch (ex) {
      apiCallCount--;
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getItemCreationNtf() async {
    try {
      if (apiCallCount == 0) Utils.showLoading(context);
      apiCallCount++;
      getItemCreationNtfBody = await WorkListApiClient().getItemCreationNtfBody(workListData!.nOTIFICATIONID!, -999);
      apiCallCount--;
      if (apiCallCount == 0) {
        Utils.hideLoading(context);
        setState(() {});
      }
    } catch (ex) {
      apiCallCount--;
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getPoNotification() async {
    try {
      if (apiCallCount == 0) Utils.showLoading(context);
      apiCallCount++;
      getPoNotificationBody = await WorkListApiClient().getPoNotificationBody(workListData!.nOTIFICATIONID!, -999);
      apiCallCount--;
      if (apiCallCount == 0) {
        Utils.hideLoading(context);
        setState(() {});
      }
    } catch (ex) {
      apiCallCount--;
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getPRNotification() async {
    try {
      if (apiCallCount == 0) Utils.showLoading(context);
      apiCallCount++;
      getPrNotificationBody = await WorkListApiClient().getPRNotificationBody(workListData!.nOTIFICATIONID!, -999);
      apiCallCount--;
      if (apiCallCount == 0) {
        Utils.hideLoading(context);
        setState(() {});
      }
    } catch (ex) {
      apiCallCount--;
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void notificationGetRespondAttributes() async {
    try {
      if (apiCallCount == 0) Utils.showLoading(context);
      apiCallCount++;
      getNotificationRespondAttributes = await WorkListApiClient().notificationGetRespondAttributes(workListData!.nOTIFICATIONID!);
      if (getNotificationRespondAttributes.isNotEmpty) {
        notificationNoteInput = getNotificationRespondAttributes.first;
      }
      apiCallCount--;
      if (apiCallCount == 0) {
        Utils.hideLoading(context);
        setState(() {});
      }
    } catch (ex) {
      apiCallCount--;
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getNotificationButtons() async {
    try {
      if (apiCallCount == 0) Utils.showLoading(context);
      apiCallCount++;
      notificationButtonsList = await WorkListApiClient().getNotificationButtons(workListData!.nOTIFICATIONID!);
      if (notificationButtonsList.isNotEmpty) {
        isCloseAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "CLOSE");
        isApproveAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "APPROVED");
        isRejectAvailable = notificationButtonsList.any((element) => element.bUTTONACTION == "REJECTED");
      }
      apiCallCount--;
      if (apiCallCount == 0) {
        Utils.hideLoading(context);
        setState(() {});
      }
    } catch (ex) {
      apiCallCount--;
      Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getActionHistory() async {
    try {
      isActionHistoryLoaded = false;
      actionHistoryList.clear();
      // if (apiCallCount == 0) Utils.showLoading(context);
      // apiCallCount++;
      actionHistoryList = await WorkListApiClient().getActionHistory(workListData!.nOTIFICATIONID!);
      // apiCallCount--;
      // if (apiCallCount == 0) {
      //   Utils.hideLoading(context);
      setState(() {
        isActionHistoryLoaded = true;
      });
      // }
    } catch (ex) {
      // apiCallCount--;
      // Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  void getAttachments() async {
    try {
      isAttachmentLoaded = false;
      getAttachmentList.clear();
      // if (apiCallCount == 0) Utils.showLoading(context);
      //  apiCallCount++;
      getAttachmentList = await WorkListApiClient().getAttachments(workListData!.nOTIFICATIONID!);
      //  apiCallCount--;
      //  if (apiCallCount == 0) {
      //   Utils.hideLoading(context);
      setState(() {
        isAttachmentLoaded = true;
      });
      //  }
    } catch (ex) {
      // apiCallCount--;
      //   Utils.hideLoading(context);
      Utils.handleException(ex, context, null);
    }
  }

  // Widget showUpdateContinueSheet(List<GetEitCollectionNotificationBodyList> list) {
  //   double itemHeight = 0;
  //   double itemWidth = 0;
  //   var size = MediaQuery.of(context).size;
  //   itemHeight = (size.height - kToolbarHeight - 24) / 9;
  //   itemWidth = size.width / 2;
  //   return Column(
  //     children: [
  //       if ((workListData?.sUBJECT ?? "").isNotEmpty) workListData!.sUBJECT!.toText14().paddingOnly(top: 10, right: 21, left: 21, bottom: 21),
  //       ListView.separated(
  //         shrinkWrap: true,
  //         physics: const NeverScrollableScrollPhysics(),
  //         itemBuilder: (cxt, index) {
  //           List<CollectionNotificationEit> dataList = list.isEmpty ? [] : (list[index].collectionNotification ?? []);
  //           dataList = dataList.where((o) => o.displayFlag == "Y").toList();
  //           bool isOdd = false;
  //           if (dataList.length % 2 != 0) {
  //             isOdd = true;
  //             dataList.add(new CollectionNotificationEit());
  //           }
  //           return GridView.builder(
  //             itemCount: dataList.length,
  //             shrinkWrap: true,
  //             physics: const NeverScrollableScrollPhysics(),
  //             itemBuilder: (context, index) => ItemDetailViewGridItem(
  //               index,
  //               dataList[index].segmentPrompt,
  //               dataList[index].segmentValueDsp,
  //               isNeedToShowEmptyDivider: (dataList.length == index + 1)
  //                   ? isOdd
  //                       ? true
  //                       : false
  //                   : false,
  //             ),
  //             gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
  //               crossAxisCount: 2,
  //               childAspectRatio: (itemWidth / itemHeight),
  //             ),
  //           ).objectContainerView();
  //         },
  //         separatorBuilder: (cxt, index) => 12.height,
  //         itemCount: list.length,
  //       ),
  //       Padding(
  //         padding: const EdgeInsets.only(right: 21, left: 21, bottom: 21),
  //         child: Row(
  //           children: [
  //             DefaultButton(
  //               LocaleKeys.edit.tr(),
  //               () => performEditAction(),
  //               colors: const [Color(0xffE47A7E), Color(0xffDE6D71)],
  //             ).expanded,
  //             8.width,
  //             DefaultButton(
  //               LocaleKeys.next.tr(),
  //               () => performNextAction(),
  //               colors: const [Color(0xff28C884), Color(0xff1BB271)],
  //             ).expanded,
  //           ],
  //         ),
  //       ),
  //     ],
  //   );
  // }

  Widget showLoadingAnimation() {
    return Lottie.asset(
      'assets/lottie/loading.json',
      repeat: true,
      reverse: false,
    );
  }
}
