import { forwardRef, isValidElement } from "react";
import { StyledIconButton } from "./icon-button.styled";
import type { IconProps } from "../icons/withSharedIconProps";
import type { ColorKey } from "../../theme";
import type { WithTestId } from "../../types";

interface IconButtonProps extends WithTestId<React.ComponentProps<typeof StyledIconButton>> {
  /**
   * Icon to display
   */
  Icon: React.FC<IconProps> | React.ReactElement;
}

/**
 * Icon button component
 */
export const IconButton = forwardRef<HTMLButtonElement, IconButtonProps>((props, ref) => {
  const { Icon, variant = "primary", type, ...rest } = props;

  const darkColor = variant === "primary" || variant === "ghost-dark";
  const iconColor: ColorKey = darkColor ? "$light-chromia-dark" : "$light-off-white";

  return (
    <StyledIconButton
      ref={ref}
      variant={variant}
      size={rest.size}
      type={type ?? "button"}
      {...rest}
    >
      {/* @ts-expect-error ts unable to correctly type narrow else branch */}
      {isValidElement(Icon) ? Icon : <Icon size={rest.size} color={iconColor} />}
    </StyledIconButton>
  );
});

IconButton.displayName = "IconButton";
