import { twJoin } from "tailwind-merge";
import React, { ComponentProps, useEffect } from "react";

import { Icon, IconProps } from "../icon/Icon";
import { Tooltip, TooltipProps } from "../tooltip/Tooltip";

export interface InputButtonProps extends ComponentProps<"button"> {
  icon: IconProps["name"];
  iconWeight?: IconProps["weight"];
  disabled?: boolean;
  tooltip?: string;
  tooltipProps?: Partial<TooltipProps>;
  className?: string;
  onClick?: () => void;
}

export const InputButton = ({
  icon,
  iconWeight = "medium",
  onClick,
  disabled = false,
  tooltip,
  tooltipProps = {},
  className,
  ...restProps
}: InputButtonProps) => {
  useIconWarning(onClick, tooltip);
  const clickable = onClick !== undefined;

  const buttonElement = (
    <button
      className={twJoin(
        "flex rounded-6 border-0 bg-transparent p-0 text-N100",
        "hover:text-N700",
        "ring-B400FR focus-visible:outline-0 focus-visible:ring-3",
        "disabled:cursor-default disabled:text-N60",
        clickable && "cursor-pointer",
        className
      )}
      onClick={onClick}
      disabled={disabled}
      {...restProps}
    >
      <Icon name={icon} weight={iconWeight} size="20" />
    </button>
  );

  return (
    <Tooltip
      tooltip={tooltip ?? ""}
      disabled={!tooltip}
      spacing="4"
      {...tooltipProps}
    >
      {disabled ? <div>{buttonElement}</div> : buttonElement}
    </Tooltip>
  );
};

/** Print a warning if the input button is used without `onClick` or a tooltip. */
function useIconWarning(
  onClick: InputButtonProps["onClick"],
  tooltip: InputButtonProps["tooltip"]
) {
  useEffect(() => {
    if (onClick === undefined && !tooltip) {
      console.warn(
        "[docoli] Input.Button: If you don't specify `onClick` or a tooltip, " +
          "use a regular icon by passing a string icon name to the`leftIcon` or`rightIcon` prop."
      );
    }
  }, [onClick, tooltip]);
}
