import cx from "classnames";
import React from "react";

import { Icon } from "../Icon";
import { Button, ButtonSize } from "./Button";

export type IconPosition = "left" | "right";

export interface IconButtonProps
  extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, "type" | "ref"> {
  /** Name of the icon */
  iconName: string;
  /** Position of the icon */
  iconPosition?: IconPosition;
  /** Class of the icon */
  iconClassName?: string;
  /** Button size. Also affects icon size */
  size?: ButtonSize;
  /** Use square button. Children are rendered as visually hidden */
  isSquare?: boolean;
  children?: React.ReactNode;
}

const IconButton = React.forwardRef<HTMLButtonElement, IconButtonProps>(
  (
    {
      iconName,
      iconPosition = "left",
      iconClassName,
      children,
      size,
      isSquare,
      ...other
    },
    ref,
  ) => {
    const IconComponent = ({ className, ...props }: { className?: string }) => (
      <Icon
        name={iconName}
        size={size ?? "medium"}
        className={cx(iconClassName, className)}
        {...props}
      />
    );

    if (isSquare) {
      return (
        <Button size={size} isSquare {...other} ref={ref}>
          <IconComponent />
          <span className="visually-hidden">{children}</span>
        </Button>
      );
    }

    return (
      <Button ref={ref} size={size} {...other}>
        {iconPosition === "left" && (
          <IconComponent className="btn__icon-left" />
        )}
        {children}
        {iconPosition === "right" && (
          <IconComponent className="btn__icon-right" />
        )}
      </Button>
    );
  },
);

IconButton.displayName = "IconButton";

export { IconButton };
