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

interface LinkIconButtonProps
  extends WithTestId<React.ComponentProps<typeof StyledLinkIconButton>> {
  /**
   * Icon to display
   */
  Icon: React.FC<IconProps> | React.ReactElement;
  /**
   * The redirect url of the LinkButton
   */
  href: string;
}

/**
 * Icon button component
 */
export const LinkIconButton = forwardRef<HTMLAnchorElement, LinkIconButtonProps>((props, ref) => {
  const { Icon, variant = "primary", ...rest } = props;

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

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

LinkIconButton.displayName = "IconButton";
