import React, { useMemo, useState } from "react";
import PropTypes from "prop-types";
import WakeComponent from "./WakeComponent";
import ActionButton from "./ActionButton";
import { Menu } from "@mui/material";
import { MoreHoriz } from "@mui/icons-material";
import { useTranslation } from "react-i18next";
import { usePermissions } from "../../../../hooks";

const ActionsGroup = ({ machine, actions, addLog }) => {
  const [menuAnchor, setMenuAnchor] = useState(null);

  const { t } = useTranslation();
  const { operateMachines: canOperateMachines } = usePermissions();

  const mainActions = useMemo(() => actions.filter(a => a.main === true), [actions]);

  const secondaryActions = useMemo(() => actions.filter(a => a.main === false), [actions]);

  const handleMenuOpen = (_, event) => {
    setMenuAnchor(event.currentTarget);
  };

  const handleMenuClose = () => {
    setMenuAnchor(null);
  };

  return (
    <>
      <div
        style={{
          display: "flex",
          flexDirection: "row",
          justifyContent: "flex-end",
          alignItems: "center"
        }}
      >
        <WakeComponent machine={machine} addLog={addLog} disabled={!canOperateMachines} />
        {mainActions.map(action => (
          <ActionButton
            key={`machine-item-${machine.machineId}-${action.code}`}
            action={action}
            machine={machine}
            disabled={!canOperateMachines}
          />
        ))}
        <ActionButton
          action={{
            code: "more",
            effect: handleMenuOpen,
            icon: MoreHoriz,
            tooltip: t("Machine.Actions.More")
          }}
          machine={machine}
        />
      </div>
      <Menu
        id="secondary-actions-menu"
        anchorEl={menuAnchor}
        keepMounted
        open={Boolean(menuAnchor)}
        onClose={handleMenuClose}
      >
        {secondaryActions.map(action => (
          <ActionButton
            key={`machine-item-${machine.machineId}-${action.code}`}
            action={action}
            machine={machine}
            callback={handleMenuClose}
            disabled={!canOperateMachines}
          />
        ))}
      </Menu>
    </>
  );
};

ActionsGroup.propTypes = {
  machine: PropTypes.shape({
    machineId: PropTypes.number.isRequired,
    machineName: PropTypes.string.isRequired,
    fullMachineName: PropTypes.string.isRequired,
    macAddress: PropTypes.string.isRequired,
    iPv4Address: PropTypes.string,
    description: PropTypes.string
  }).isRequired,
  actions: PropTypes.array.isRequired,
  addLog: PropTypes.func.isRequired
};

export default ActionsGroup;
