import React, { useContext, FC } from 'react';
import { FaCheck, FaZhihu } from 'react-icons/fa';
import cn from 'classnames';

import { MenuContext } from '../context';
import { MenuItemProps } from '../types.d';
import { useTheme } from '../../Theme';
import { StyledMenuItem } from '../styled-components';
import { StyledSecondaryIcon } from '../../StyledComponents';

const emptyIcon = () => <FaZhihu style={{ visibility: 'hidden' }} />;

const SquareMenuItem: FC<MenuItemProps> = ({
  title,
  onClick = () => {},
  icon = null,
  isRenderEmptyIcon,
  style = {},
  isSelected = false,
  className = '',
  isDisabledAutoClose = false,
}) => {
  const theme = useTheme();
  const { toggleMenu } = useContext(MenuContext);

  const renderIcon = () => {
    if (isSelected) return <FaCheck />;
    if (isRenderEmptyIcon) return emptyIcon();
    return icon;
  };

  const menuItemClass = cn({
    'square-menu-item': true,
    className,
  });

  return (
    <StyledMenuItem
      className={menuItemClass}
      selected={isSelected}
      $theme={theme}
      style={style}
      onClick={(e) => {
        onClick();
        if (!isDisabledAutoClose) toggleMenu(e as unknown as React.MouseEvent<HTMLButtonElement, MouseEvent>);
      }}
    >
      <StyledSecondaryIcon className="square-menu-item-icon" $selected={isSelected} $theme={theme}>
        {renderIcon()}
      </StyledSecondaryIcon>
      {title}
    </StyledMenuItem>
  );
};

export class MenuItem extends React.PureComponent<MenuItemProps> {
  render(): React.ReactElement {
    // eslint-disable-next-line react/jsx-props-no-spreading
    return <SquareMenuItem {...this.props} />;
  }
}
