import { MouseEventHandler, ReactNode, useState } from 'react';
import type { MenuProps as MuiMenuProps } from '@mui/material/Menu';
import { ASSETS_URL } from '../../../consts/common';
import { ButtonProps } from '../../button';
import { LinkProps } from '../link';
import { StyledLearnMoreItem, StyledLearnMoreLink, StyledButton, StyledMenu } from './styles';

export interface LearnMoreMenuButtonProps {
  /**
   * Will be rendered inside the menu as Link components.
   */
  links: (LinkProps & { text?: string })[];
  /**
   * The text of the button.
   */
  buttonText: ReactNode;
  /**
   * Props forwarded to the Button component.
   */
  buttonProps?: ButtonProps;
  /**
   * Props forwarded to the MuiMenu component.
   */
  menuProps?: MuiMenuProps;
}

const LearnMoreMenuButton = ({
  links,
  buttonProps,
  buttonText,
  menuProps
}: LearnMoreMenuButtonProps) => {
  const [anchorEl, setAnchorEl] = useState<Element>();

  const handleClose = () => setAnchorEl(undefined);

  const handleOpen: MouseEventHandler<HTMLButtonElement> = e => {
    setAnchorEl(e.currentTarget);
    if (buttonProps?.onClick) buttonProps.onClick(e);
  };
  return (
    <>
      <StyledButton
        sx={{ height: 'auto' }}
        variant="text"
        endIconUrl={`${ASSETS_URL}/icons/icon_arrow.svg`}
        size="small"
        clickArea={false}
        {...buttonProps}
        onClick={handleOpen}
      >
        {buttonText}
      </StyledButton>
      <StyledMenu
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'right'
        }}
        transformOrigin={{
          vertical: -4,
          horizontal: 21
        }}
        open={!!anchorEl}
        anchorEl={anchorEl}
        onClose={handleClose}
        transitionDuration={0}
        {...menuProps}
      >
        {links.map((linkProps, index) => {
          const { children, id, text, ...otherProps } = linkProps;

          return (
            <StyledLearnMoreItem key={id || index} onClick={handleClose}>
              <StyledLearnMoreLink target="_blank" table rel="noreferrer noopener" {...otherProps}>
                {text || children}
              </StyledLearnMoreLink>
            </StyledLearnMoreItem>
          );
        })}
      </StyledMenu>
    </>
  );
};

export default LearnMoreMenuButton;
