import React, { useState, useRef } from 'react';
import { MoreVert } from '@mui/icons-material';
import { Popover, Typography } from '@mui/material';
import PropTypes from 'prop-types';
import './ActionForPermission.css';

function ActionForPermission(props) {
  const [anchorEl, setAnchorEl] = useState(null);
  const menuRef = useRef(null);

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleEditPermissions = (actionType) => {
    props.handleModifyPermissions(props.userData, actionType);
    handleClose();
  };

  const open = Boolean(anchorEl);
  const id = open ? 'simple-popover' : undefined;

  return (
    <div className="action-button" ref={menuRef}>
      <button
        aria-describedby={id}
        onClick={handleClick}
        className="icon-button"
        type="button"
      >
        <MoreVert />
      </button>

      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
      >
        <Typography component="div">
          <div className="box">
            <button
              className="element"
              type="button"
              onClick={() => handleEditPermissions('addEdit')}
            >
              Edit
            </button>

            <button
              className="element"
              type="button"
              onClick={() => handleEditPermissions('delete')}
            >
              Delete
            </button>
          </div>
        </Typography>
      </Popover>
    </div>
  );
}

ActionForPermission.propTypes = {
  handleModifyPermissions: PropTypes.func.isRequired,
  userData: PropTypes.object.isRequired,
};

export default ActionForPermission;
