import type { Ref, RefAttributes, ReactNode, ReactElement } from "react";
import { cloneElement, isValidElement, Children } from "react";
import classNames from "classnames/dedupe";
import type { DOMProps } from "../../types/dom";

export type ItemElementType = HTMLLIElement;

export interface ItemProps extends DOMProps, RefAttributes<ItemElementType> {
  elementType?: React.ElementType;
  /** Custom class name for setting specific CSS */
  className?: string;
  active?: boolean;
  children?: ReactNode;
  onClick?: () => void;
}

export type ItemRef = Ref<ItemElementType>;

const Item = ({ ref, ...props }: ItemProps) => {
  const {
    elementType: Element = "li",
    active,
    onClick,
    children,
    ...otherProps
  } = props;
  const classes = classNames(
    "mobius",
    "mobius-dropdown-menu__item",
    { "--is-active": active },
    otherProps.className,
  );

  return (
    <Element ref={ref} onClick={onClick} {...otherProps}>
      {Children.map(children, child => {
        if (isValidElement(child)) {
          const childClasses = classNames(
            (child.props as { className?: string }).className,
            classes,
          );
          return cloneElement(child as ReactElement<{ className?: string }>, {
            className: childClasses,
          });
        }

        return <span className={classes}>{child}</span>;
      })}
    </Element>
  );
};

Item.displayName = "DropdownMenu.Item";
export { Item };
