import { useState } from 'react';
import { Menu, MenuItem, IconButton } from '@mui/material';
import MoreVertIcon from '@mui/icons-material/MoreVert';
import { DeleteUserModal } from './DeleteUserModal';
import { EditUserModal } from './EditUserModal';

const RowActionsMenu = ({ row, onEditSsp, onEdit, onDelete }) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const open = Boolean(anchorEl);
  const [openModalDelete, setOpenModalDelete] = useState(false);
  const [openModalEdit, setOpenModalEdit] = useState(false);

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

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

  const handleEdit = (user) => {
    handleClose();
    onEdit(user);
  };

  const handleDelete = () => {
    handleClose();
    onDelete(row.original.id);
  };

  return (
    <>
      <IconButton
        size="small"
        onClick={handleClick}
        aria-controls={open ? 'row-menu' : undefined}
        aria-haspopup="true"
        aria-expanded={open ? 'true' : undefined}
      >
        <MoreVertIcon />
      </IconButton>

      <Menu
        id="row-menu"
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'right',
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'right',
        }}
        sx={{
          '& .MuiPaper-root': {
            borderRadius: '0.75rem',
            boxShadow: '0 4px 15px 0 gray',
          },
          '& li': {
            padding: ' 0.38rem 0.5rem 0.38rem 0.75rem',
            fontSize: '0.75rem',
          },
        }}
      >
        <MenuItem
          onClick={() => {
            handleClose();
            setOpenModalEdit(true);
          }}
        >
          Редактировать
        </MenuItem>
        <MenuItem
          onClick={() => {
            handleClose();
            setOpenModalDelete(true);
          }}
          sx={{ color: 'error.main' }}
        >
          Удалить
        </MenuItem>
      </Menu>
      <DeleteUserModal
        isOpen={openModalDelete}
        onClose={() => {
          setOpenModalDelete(false);
        }}
        onConfirm={handleDelete}
        user={row.original}
      />
      <EditUserModal
        isOpen={openModalEdit}
        onClose={() => {
          setOpenModalEdit(false);
        }}
        onConfirm={handleEdit}
        onEditSsp={onEditSsp}
        user={row.original}
      />
    </>
  );
};

export default RowActionsMenu;
