'use client'

import { Slot } from '@radix-ui/react-slot'
import { cva, type VariantProps } from 'class-variance-authority'
import type * as React from 'react'
import { cn } from '../../utils/cn'
import { buttonVariants } from './Button'

export const BUTTON_ICON_SIZE_OPTIONS = ['default', 'sm', 'xs'] as const
export type ButtonIconSize = (typeof BUTTON_ICON_SIZE_OPTIONS)[number]

export const BUTTON_ICON_VARIANT_OPTIONS = ['default', 'ghost'] as const
export type ButtonIconVariant = (typeof BUTTON_ICON_VARIANT_OPTIONS)[number]

// Create a CVA for the ButtonIcon size variants
const buttonIconVariants = cva('', {
  variants: {
    variant: {
      default: cn(
        buttonVariants({
          variant: 'tertiary',
          width: 'full',
        }),
        'text-tertiary-foreground',
      ),
      ghost: cn(
        buttonVariants({
          variant: 'ghost',
          width: 'full',
        }),
        'text-ghost-foreground',
      ),
    },
    size: {
      default: 'p-4 size-12 min-h-12 min-w-12 max-w-12 [&_svg]:size-4',
      sm: 'p-3.5 size-10 min-h-10 min-w-10 max-w-10 [&_svg]:size-3',
      xs: 'p-2.5 size-8 min-h-8 min-w-8 max-w-8 [&_svg]:size-3',
    },
  },
  defaultVariants: {
    variant: 'default',
    size: 'default',
  },
})

export interface ButtonIconProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof buttonIconVariants> {
  asChild?: boolean
  ref?: React.Ref<HTMLButtonElement>
}

const ButtonIcon = ({
  className,
  asChild = false,
  size,
  variant,
  ref,
  ...props
}: ButtonIconProps) => {
  const Comp = asChild ? Slot : 'button'
  return (
    <Comp
      className={cn(buttonIconVariants({ size, variant }), className)}
      ref={ref}
      {...props}
    />
  )
}
ButtonIcon.displayName = 'ButtonIcon'

export { ButtonIcon, buttonVariants, buttonIconVariants }
