import { MenuPopover } from '@/components/MenuPopover';
import { MoreHoriz, MoreVert } from '@mui/icons-material';
import { IconButton, MenuItem, styled } from '@mui/material';
import React, { Children, PropsWithChildren, useCallback, useState } from 'react';

const BUTTON_STYLES = { width: '100%', justifyContent: 'flex-start' };

const StyledRoot = styled('div', {
  shouldForwardProp: (prop) => prop !== 'color' && prop !== 'variant' && prop !== 'sx',
  slot: 'root',
  overridesResolver: (_, styles) => [styles.root]
})(() => ({
  textAlign: 'right'
}));

const StyledMenuPopover = styled(MenuPopover, {
  slot: 'root'
})(({ theme }) => ({
  '& .MuiMenuItem-root': {
    padding: 0,
    margin: 0,
    '& .MuiButton-startIcon': {
      marginRight: theme.spacing(0)
    },
    [theme.breakpoints.down('sm')]: {
      '&>.MuiSvgIcon-root, & svg': {
        marginRight: theme.spacing(0)
      }
    }
  }
}));

type ActionsMenuProps = PropsWithChildren<{ horizontal?: boolean; disabled?: boolean }>;

/**
 * Allows you to draw a menu of actions grouped within a popover.
 * Inside the menu you can insert one or more components that, it is advisable, are buttons.
 *
 * @example
 * <ActionsMenu>
 *  <DeleteButton />
 *  <EditButton />
 * </ActionsMenu>
 */
function ActionsMenu({ horizontal = false, disabled = false, children }: ActionsMenuProps): React.ReactElement | null {
  const [open, setOpen] = useState(null);
  const actionRef = React.useRef(null);

  function handleClick(e: any): void {
    e.stopPropagation();
    e.preventDefault();
    setOpen(e.currentTarget);
    actionRef.current = e.currentTarget;
  }
  const handleClose = useCallback((e: any) => {
    e.stopPropagation();
    e.preventDefault();
    setOpen(null);
  }, []);
  const handleOnClick = useCallback((e: any) => {
    setOpen(null);

    if (typeof e.currentTarget?.onClick === 'function') {
      e.currentTarget.onClick(e);
    }
  }, []);
  if (
    !children ||
    React.Children.count(children) === 0 ||
    // @ts-ignore
    (children?.filter && children?.filter((c) => React.isValidElement(c)).length === 0)
  ) {
    return null;
  }

  return (
    <StyledRoot>
      <IconButton
        aria-label="more"
        aria-haspopup="true"
        onClick={handleClick}
        color={open ? 'inherit' : 'default'}
        disabled={disabled}
      >
        {horizontal ? <MoreHoriz /> : <MoreVert />}
      </IconButton>
      {/* @ts-ignore */}
      <StyledMenuPopover open={open} onClose={handleClose} arrow="right-top">
        {Children.map(
          children,
          (action, index) =>
            React.isValidElement(action) && (
              <MenuItem onClick={handleOnClick} key={index}>
                {React.cloneElement(action, {
                  // @ts-ignore
                  style: { ...BUTTON_STYLES }
                })}
              </MenuItem>
            )
        )}
      </StyledMenuPopover>
    </StyledRoot>
  );
}

export { ActionsMenu };
export type { ActionsMenuProps };
