import { Slot as SlotPrimitive } from "radix-ui";
import * as React from "react";
import { ButtonContext, handleEnterPress } from "../Link";
import { TooltipSymbol } from "../Tooltip";

export interface ButtonProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  size?: "xs" | "sm" | "md" | "lg";
  variant?: "solid" | "outline" | "ghost" | "subtle" | "elvated";
  colorPalette?: string;
  asChild?: boolean;
}

export function MaybeButton(props: React.ComponentPropsWithRef<"button">) {
  const inButton = React.use(ButtonContext);
  if (inButton) {
    return (
      <span
        role="button"
        tabIndex={0}
        onKeyDown={handleEnterPress}
        aria-disabled={props.disabled as boolean}
        onClick={props.disabled ? undefined : props.onClick}
        {...props}
      />
    );
  }
  return (
    <ButtonContext value={true}>
      <button {...props} />
    </ButtonContext>
  );
}

export const Button = ({
  variant = "subtle",
  size = "md",
  asChild = false,
  onClick,
  ...props
}: ButtonProps) => {
  const Comp = asChild ? SlotPrimitive.Slot : MaybeButton;
  return (
    <Comp
      data-variant={variant}
      data-size={size}
      onClick={onClick}
      data-component="Button$Brevity"
      {...props}
    />
  );
};
Button[TooltipSymbol] = true;

export const IconButton = Button;
