import React, { forwardRef, useCallback } from "react";
import cn from "classnames";
import PropTypes from "prop-types";
import { getPressedKey, KEYS } from "../utils/keyboard";
import { AsComponent, AsPropsWithChildren } from "../utils/asComponent";

export interface IDropdownItemProps extends AsPropsWithChildren {
  role?: string;
  isActive?: boolean;
  isDisabled?: boolean;
  href?: string;
  onClick?: (event: React.SyntheticEvent) => void;
  eventKey?: string;
  title?: string;
  tabIndex?: number;
}

type DropdownItem = AsComponent<"a", IDropdownItemProps>;
const DropdownItem: DropdownItem = forwardRef(
  (
    {
      isActive,
      role,
      isDisabled,
      className,
      onClick,
      children,
      tabIndex,
      as: Component = "a",
      ...props
    },
    ref
  ) => {
    const onKeyPress = useCallback(
      (e: React.KeyboardEvent) => {
        if (!onClick) {
          return;
        }
        const key = getPressedKey(e);
        if (key === KEYS.Enter) {
          onClick(e);
        }
      },
      [onClick]
    );

    return (
      <Component
        {...props}
        role={role}
        ref={ref}
        onClick={onClick}
        onKeyPress={onKeyPress}
        tabIndex={tabIndex || 0}
        className={cn(
          "dropdown-item",
          "text-truncate",
          { active: isActive, disabled: isDisabled },
          className
        )}
      >
        {children}
      </Component>
    );
  }
);

DropdownItem.displayName = "DropdownItem";

DropdownItem.propTypes = {
  role: PropTypes.string,
  className: PropTypes.string,
  isActive: PropTypes.bool,
  isDisabled: PropTypes.bool,
  href: PropTypes.string,
  onClick: PropTypes.func,
  eventKey: PropTypes.string
};

DropdownItem.defaultProps = {
  as: "a"
};

export default DropdownItem;
