import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { Loader2 } from "lucide-react"
import { type VariantProps } from "class-variance-authority"

import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button-variants"

export interface ButtonProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof buttonVariants> {
  asChild?: boolean
  loading?: boolean
  loadingLabel?: React.ReactNode
  leadingIcon?: React.ReactNode
  spinnerClassName?: string
}

const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
  ({
    className,
    variant,
    size,
    asChild = false,
    loading = false,
    loadingLabel,
    leadingIcon,
    spinnerClassName,
    children,
    disabled,
    ...props
  }, ref) => {
    const Comp = asChild ? Slot : "button"
    return (
      <Comp
        className={cn(buttonVariants({ variant, size, className }))}
        disabled={disabled || loading}
        aria-busy={loading || undefined}
        ref={ref}
        {...props}
      >
        {loading ? (
          <Loader2 className={cn("h-4 w-4 animate-spin", spinnerClassName)} />
        ) : (
          leadingIcon
        )}
        {loading && loadingLabel ? loadingLabel : children}
      </Comp>
    )
  }
)
Button.displayName = "Button"

export { Button }
