import React from "react";
import { Menu } from "antd";
import i18next, { t } from "i18next";
import { useDispatch, useSelector } from "react-redux";
import store from "../../store";
import {
  hideDataOnTable,
  setSelectedRowKeys,
  setSelectedObject,
  updateVisibleScheduleDialog,
} from "../../store/AllOperationListSlice";
import { alertError, alertInfo, confirmDialog } from "../dialogs/CommonDialog";
import JobExecutionService from "../../services/jobExecutionService";
import {
  LOAD_STATUS_TYPE,
  RESPONSE_OBJ_KEY,
  RUN_JOB_STATUS_TYPE,
  SERVICE_RESPONSE,
  START_PEND_FLAG,
} from "../../constants";
import { all } from "axios";

const JobExecutionAllTableContextMenu = ({ value, tableType, record }) => {
  const t = i18next.t;
  const dispatch = useDispatch();
  const detail = useSelector((state) => state.allOperationList.selectedObject);
  var hideMenuItemDisabled = true;
  var stopMenuItemDisabled = true;
  var delayMenuItemDisabled = true;
  var updateScheduleMenuItemDisabled = true;
  var holdMenuItemDisabled = true;
  var releaseMenuItemDisabled = true;
  var scheduleDeleteMenuItemDisabled = true;

  const allItemsDisable = () => {
    stopMenuItemDisabled = true;
    delayMenuItemDisabled = true;
    updateScheduleMenuItemDisabled = true;
    holdMenuItemDisabled = true;
    releaseMenuItemDisabled = true;
    scheduleDeleteMenuItemDisabled = true;
  };

  const multipleScheduleEnabled = () => {
    stopMenuItemDisabled = false;
    scheduleDeleteMenuItemDisabled = false;
  };

  const scheduleEnabled = () => {
    stopMenuItemDisabled = false;
    updateScheduleMenuItemDisabled = false;
    holdMenuItemDisabled = false;
    scheduleDeleteMenuItemDisabled = false;
  };

  const multipleScheduleWaitingDisabled = () => {
    stopMenuItemDisabled = false;
    updateScheduleMenuItemDisabled = true;
    scheduleDeleteMenuItemDisabled = true;
    holdMenuItemDisabled = false;
  }

  const onHoldMultipleScheduleWaitingDisabled = () => {
    stopMenuItemDisabled = false;
    updateScheduleMenuItemDisabled = true;
    scheduleDeleteMenuItemDisabled = true;
    releaseMenuItemDisabled = false;
  }

  const onholdScheduleEnabled = () => {
    stopMenuItemDisabled = false;
    updateScheduleMenuItemDisabled = false;
    releaseMenuItemDisabled = false;
    scheduleDeleteMenuItemDisabled = false;
  };

  const delayscheduleEnabled = () => {
    stopMenuItemDisabled = false;
    delayMenuItemDisabled = false;
  };

  //all disable except stop
  const runningEnabled = () => {
    stopMenuItemDisabled = false;
  };

  const isNormalStatus = (item) =>
    parseInt(item.intStatus) === RUN_JOB_STATUS_TYPE.NORMAL;
  const isNoneStatus = (item) =>
    parseInt(item.intStatus) === RUN_JOB_STATUS_TYPE.NONE;
  const isDuringStatus = (item) =>
    parseInt(item.intStatus) === RUN_JOB_STATUS_TYPE.DURING;
  const isDelayStatus = (item) =>
    parseInt(item.loadStatus) === LOAD_STATUS_TYPE.DELAY;

  const someItemsWithStatus = (detail, statusCheck) => detail.some(statusCheck);
  const everyItemWithStatus = (detail, statusCheck) =>
    detail.every(statusCheck);

  if (detail.length === 1) {
    const jobStatus = parseInt(detail[0].intStatus);
    const loadStatus = parseInt(detail[0].loadStatus);
    const startPendingFlag = parseInt(detail[0].startPendingFlag);
    const scheduledTime = detail[0].scheduledTime;
    
    //only one item selected
    switch (jobStatus) {
      //Schedule Job Status
      case RUN_JOB_STATUS_TYPE.NONE:

        if(scheduledTime === "0"){
          if (startPendingFlag === START_PEND_FLAG.PENDING){
              onHoldMultipleScheduleWaitingDisabled();
          }else{
              multipleScheduleWaitingDisabled();
          }
        }else{
          if(startPendingFlag === START_PEND_FLAG.PENDING){
            onholdScheduleEnabled();
          }else{
            scheduleEnabled();
          }
        }
        break;

      //Running Job Status
      case RUN_JOB_STATUS_TYPE.DURING:
        if (loadStatus === LOAD_STATUS_TYPE.DELAY) {
          delayscheduleEnabled();
        } else {
          runningEnabled();
        }
        break;
      default:
        allItemsDisable();
        break;
    }
  } else if (detail.length > 1) {
    if (someItemsWithStatus(detail, isNormalStatus)) {
      allItemsDisable();
    } else if (everyItemWithStatus(detail, isNoneStatus)) {
      multipleScheduleEnabled();
    } else if (
      (someItemsWithStatus(detail, isDuringStatus) &&
        someItemsWithStatus(detail, isNoneStatus)) ||
      everyItemWithStatus(detail, isDuringStatus)
    ) {
      runningEnabled();
      if (everyItemWithStatus(detail, isDelayStatus)) {
        delayMenuItemDisabled = false;
      }
    }
  }

  const jobExecManagementItems = [
    {
      id: "btnhide",
      label: t("btn-hide"),
      key: "item-1",
      onClick: () => {
        if (store.getState().allOperationList.selectedRow.length === 0) {
          alertError(t("title-error"), t("err-msg-no-select-data"));
        } else {
          store.dispatch(hideDataOnTable());
        }
      },
      disabled: hideMenuItemDisabled,
    },
    {
      id: "btnstop",
      label: t("btn-stop"),
      key: "item-2",
      onClick: () => {
        if (store.getState().allOperationList.selectedRow.length === 0) {
          alertError(t("title-error"), t("err-msg-no-select-data"));
        } else {
          JobExecutionService.stopAllJobnetSummary({
            innerJobnetIdList: store.getState().allOperationList.selectedRow,
            statusList: store
              .getState()
              .allOperationList.selectedObject.map(
                (object) => object.intStatus
              ),
          }).then((res) => {
            store.dispatch(setSelectedRowKeys([]));
            store.dispatch(setSelectedObject([]));
            if (res.type === SERVICE_RESPONSE.OK) {
              // dispatch(getAllOperationList());
            } else {
              alertError(t("title-error"), res.error.message);
            }
          });
        }
      },
      disabled: stopMenuItemDisabled,
    },
    {
      id: "btndelay",
      label: t("btn-delay"),
      key: "item-3",
      onClick: () => {
        if (store.getState().allOperationList.selectedRow.length === 0) {
          alertError(t("title-error"), t("err-msg-no-select-data"));
        } else {
          JobExecutionService.delayJobnetSummary({
            innerJobnetIdList: store.getState().allOperationList.selectedRow,
            loadStatusList: store
              .getState()
              .allOperationList.selectedObject.map(
                (object) => object.loadStatus
              ),
          }).then((res) => {
            if (res.type === SERVICE_RESPONSE.OK) {
              // dispatch(getAllOperationList());
            } else {
              alertError(t("title-error"), res.error.message);
            }
          });
        }
      },
      disabled: delayMenuItemDisabled,
    },
    {
      id: "btnupdschd",
      label: t("btn-upd-schd"),
      key: "item-4",
      onClick: () => {
        if (store.getState().allOperationList.selectedRow.length === 0) {
          alertError(t("title-error"), t("err-msg-no-select-data"));
        } else {
          dispatch(updateVisibleScheduleDialog(true));
        }
      },
      disabled: updateScheduleMenuItemDisabled,
    },
    {
      id: "btnhold",
      label: t("btn-hold-ctx-menu"),
      key: "item-5",
      onClick: () => {
        if (store.getState().allOperationList.selectedRow.length === 0) {
          alertError(t("title-error"), t("err-msg-no-select-data"));
        } else {
          JobExecutionService.holdJobnetSummary({
            innerJobnetIdList: store.getState().allOperationList.selectedRow,
          }).then((res) => {
            store.dispatch(setSelectedRowKeys([]));
            store.dispatch(setSelectedObject([]));
            if (res.type === SERVICE_RESPONSE.OK) {
              // dispatch(getAllOperationList());
            } else {
              alertError(t("title-error"), res.error.message);
            }
          });
        }
      },
      disabled: holdMenuItemDisabled,
    },
    {
      id: "btnrelease",
      label: t("btn-release"),
      key: "item-6",
      onClick: () => {
        if (store.getState().allOperationList.selectedRow.length === 0) {
          alertError(t("title-error"), t("err-msg-no-select-data"));
        } else {
          JobExecutionService.releaseJobnetSummary({
            innerJobnetIdList: store.getState().allOperationList.selectedRow,
          }).then((res) => {
            store.dispatch(setSelectedRowKeys([]));
            store.dispatch(setSelectedObject([]));
            if (res.type === SERVICE_RESPONSE.OK) {
              // dispatch(getAllOperationList());
            } else {
              alertError(t("title-error"), res.error.message);
            }
          });
        }
      },
      disabled: releaseMenuItemDisabled,
    },
    {
      id: "btnschddel",
      label: t("btn-schd-del"),
      key: "item-7",
      onClick: () => {
        if (store.getState().allOperationList.selectedRow.length === 0) {
          alertError(t("title-error"), t("err-msg-no-select-data"));
        } else {
          let scheduleIdList = store
            .getState()
            .allOperationList.selectedObject.map((object) => object.scheduleId);
          let innerJobnetIdList = store.getState().allOperationList.selectedRow;
          // Check if scheduleIdList is an array and proceed only if it has elements
          if (Array.isArray(scheduleIdList) && scheduleIdList.length > 0) {
            for (const scheduleId of scheduleIdList) {
              if (scheduleId === null) {
                alertError(t("title-error"), t("err-msg-no-schedule-id"));
                return;
              }
            }
          }
          JobExecutionService.checkScheduleValid({
            scheduleIdList,
          }).then((res) => {
            if (res.type === SERVICE_RESPONSE.OK) {
              if (res.detail.message === SERVICE_RESPONSE.INVALID) {
                confirmDialog(
                  t("title-msg-conf"),
                  t("warn-msg-del"),
                  () => {
                    JobExecutionService.deleteSchedule({
                      innerJobnetIdList,
                      scheduleIdList,
                    }).then((res) => {
                      if (res.type === SERVICE_RESPONSE.OK) {
                        store.dispatch(setSelectedRowKeys([]));
                        store.dispatch(setSelectedObject([]));
                        // dispatch(getAllOperationList());
                      } else {
                        if (res.type === SERVICE_RESPONSE.INCOMEPLETE) {
                          if (
                            res.detail.hasOwnProperty(
                              RESPONSE_OBJ_KEY.MESSAGE_CODE
                            )
                          ) {
                            alertInfo(
                              t("title-info"),
                              t(res.detail[RESPONSE_OBJ_KEY.MESSAGE_CODE])
                            );
                          } else {
                            alertError(
                              t("title-error"),
                              t("err-msg-schedule-enable", {
                                id: res.detail.validScheduleId,
                              })
                            );
                          }
                        }
                      }
                    });
                  },
                  () => {}
                );
              } else {
                alertError(
                  t("title-error"),
                  t("err-msg-schedule-enable", {
                    id: res.detail.validScheduleId,
                  })
                );
              }
            } else {
            }
          });
        }
      },
      disabled: scheduleDeleteMenuItemDisabled,
    },
  ];

  return <Menu items={jobExecManagementItems} />;
};
export default JobExecutionAllTableContextMenu;
