import React, { type ReactElement, type ReactNode } from "react";
import {
  ListItemIcon,
  MenuItem as MUIMenuItem,
  type MenuItemProps as MUIMenuItemProps,
} from "@mui/material";
import { twJoin } from "tailwind-merge";

import { Icon, type IconProps } from "../icon/Icon";
import { Typography } from "../typography/Typography";
import { twMerge } from "../../../tailwind.config";
import { useMenuItemStyles } from "./MenuItem.styles";

export interface MenuItemProps
  extends Omit<MUIMenuItemProps, "button" | "className"> {
  children: string | number | ReactNode;
  color?: "main" | "danger" | "action";
  leftIcon?: IconProps["name"] | ReactElement;
  rightIcon?: IconProps["name"] | ReactElement;
  disabled?: boolean;
  onClick?: (e: React.MouseEvent<HTMLLIElement>) => void;
  ESCAPE_className?: string;
}

const iconStyles = "min-w-[auto] text-[inherit]";

export const MenuItem = React.forwardRef<HTMLLIElement, MenuItemProps>(
  (
    {
      children,
      color = "main",
      leftIcon,
      rightIcon,
      disabled = false,
      onClick,
      ESCAPE_className,
      ...restProps
    },
    ref
  ) => {
    const menuItemClasses = useMenuItemStyles({ color, disabled });

    const handleClick = (e: React.MouseEvent<HTMLLIElement>) => {
      if (onClick) {
        e.stopPropagation();
        onClick(e);
      }
    };

    return (
      <MUIMenuItem
        classes={{
          ...menuItemClasses,
          root: twMerge(menuItemClasses.root, ESCAPE_className),
        }}
        disabled={disabled}
        onClick={(e) => {
          !disabled && handleClick(e);
        }}
        ref={ref}
        {...restProps}
      >
        {leftIcon && (
          <div
            style={{ height: "20px", display: "flex", alignItems: "center" }}
          >
            <ListItemIcon classes={{ root: twJoin(iconStyles, "mr-8") }}>
              {typeof leftIcon === "string" ? (
                <Icon name={leftIcon} size="20" weight="medium" />
              ) : (
                leftIcon
              )}
            </ListItemIcon>
          </div>
        )}
        <div className="flex-1">
          <Typography size="200" color="inherit">
            {children}
          </Typography>
        </div>
        {rightIcon && (
          <div
            style={{ height: "20px", display: "flex", alignItems: "center" }}
          >
            <ListItemIcon classes={{ root: twJoin(iconStyles, "ml-8") }}>
              {typeof rightIcon === "string" ? (
                <Icon name={rightIcon} size="20" weight="medium" />
              ) : (
                rightIcon
              )}
            </ListItemIcon>
          </div>
        )}
      </MUIMenuItem>
    );
  }
);

MenuItem.displayName = "MenuItem";
