import * as React from 'react'

import {cva, type VariantProps} from 'class-variance-authority'
import {Slot as SlotPrimitive} from 'radix-ui'

import {cn} from '../../lib/utils'

const buttonVariants = cva(
  "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:bg-disabled disabled:text-disabled-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none aria-invalid:border-destructive",
  {
    variants: {
      variant: {
        default: 'bg-primary text-primary-foreground',
        secondary: 'bg-secondary text-secondary-foreground',
        tertiary: 'bg-tertiary text-tertiary-foreground',
        destructive: 'bg-destructive text-white dark:bg-destructive/60',
        outline: 'border bg-background dark:bg-input/30 dark:border-input',
        ghost: '',
        link: 'text-primary underline-offset-4',
        icon: 'flex rounded-full items-center justify-center p-0 aspect-square',
      },
      size: {
        default:
          'min-h-[32px] rounded-lg px-3 py-2 text-sm leading-[18px] has-[>svg]:px-3',
        sm: 'min-h-[20px] rounded-lg gap-1.5 px-3 py-1 text-xs leading-4 has-[>svg]:px-2.5',
        lg: 'min-h-[44px] rounded-xl px-3 py-3 text-base leading-6 has-[>svg]:px-4',
      },
    },
    compoundVariants: [
      {
        variant: 'icon',
        size: 'default',
        className:
          'size-8 min-h-0 p-0 rounded-full gap-0 px-0 py-0 has-[>svg]:px-0',
      },
      {
        variant: 'icon',
        size: 'sm',
        className:
          'size-6 min-h-0 p-0 rounded-full gap-0 px-0 py-0 has-[>svg]:px-0',
      },
      {
        variant: 'icon',
        size: 'lg',
        className:
          'size-10 min-h-0 p-0 rounded-full gap-0 px-0 py-0 has-[>svg]:px-0',
      },
    ],
    defaultVariants: {
      variant: 'default',
      size: 'default',
    },
  }
)

function BaseButton({
  className,
  variant,
  size,
  asChild = false,
  ...props
}: React.ComponentProps<'button'> &
  VariantProps<typeof buttonVariants> & {
    asChild?: boolean
  }) {
  const Comp = asChild ? SlotPrimitive.Slot : 'button'

  return (
    <Comp
      data-slot="button"
      className={cn(buttonVariants({variant, size, className}))}
      {...props}
    />
  )
}

export {BaseButton, buttonVariants}
