import React, { FunctionComponent, useEffect, useRef } from 'react';
import { Fade, IconButton } from '@material-ui/core';

import { AiFillSetting } from 'react-icons/ai';

import { useTheme } from '../Theme';
import { StyledSecondaryIcon } from '../StyledComponents';
import { MenuProps, MenuItemProps } from './types.d';
import { StyledMenu } from './styled-components';
import { useInitMenuContext, MenuContext } from './context';
import { MenuItem, MenuTitle, MenuDivider, MenuItems } from './components';

const SquareMenu: FunctionComponent<MenuProps> = ({
  PaperProps,
  anchor,
  children,
  className = '',
  disabled = false,
  isOpen,
  setIsOpen,
  style = {},
}): React.ReactElement => {
  const theme = useTheme();

  const anchorRef = useRef<EventTarget & HTMLButtonElement>(null);

  const menuContext = useInitMenuContext(setIsOpen);

  const open = Boolean(isOpen ?? menuContext.optionsAnchorEl);

  useEffect(() => {
    if (isOpen && anchorRef.current) menuContext.setOptionsAnchorEl(anchorRef.current);
  }, [isOpen]);

  const renderAnchor = () => {
    if (!anchor)
      return (
        <StyledSecondaryIcon className="square-menu-anchor" $theme={theme} aria-controls="simple-menu" aria-haspopup="true">
          <AiFillSetting />
        </StyledSecondaryIcon>
      );
    return (
      <StyledSecondaryIcon className="square-menu-anchor" $theme={theme} aria-controls="simple-menu" aria-haspopup="true">
        {anchor}
      </StyledSecondaryIcon>
    );
  };

  return (
    <MenuContext.Provider value={menuContext}>
      <div className={`square-menu ${className}`} style={style}>
        <IconButton
          style={{ padding: 0 }}
          disabled={disabled}
          aria-controls="fade-menu"
          disableRipple
          aria-haspopup="true"
          role="button"
          tabIndex={0}
          onKeyDown={() => {}}
          ref={anchorRef}
          onClick={menuContext.toggleMenu}
        >
          {renderAnchor()}
        </IconButton>
        <StyledMenu
          id="simple-menu"
          anchorEl={menuContext.optionsAnchorEl}
          keepMounted
          open={open}
          onClose={menuContext.toggleMenu}
          TransitionComponent={Fade}
          $theme={theme}
          PaperProps={PaperProps ?? {}}
        >
          {children}
        </StyledMenu>
      </div>
    </MenuContext.Provider>
  );
};

export const Menu = Object.assign(SquareMenu, {
  Title: MenuTitle as unknown as React.FC<MenuItemProps>,
  Item: MenuItem as unknown as React.FC<MenuItemProps>,
  Items: MenuItems,
  Divider: MenuDivider,
});
