import * as React from 'react';

import { Slot } from '@radix-ui/react-slot';
import { type VariantProps, cva } from 'class-variance-authority';

import styles from './BaseButton.module.css';

import { cn } from '@/utils';

const baseButtonVariants = cva(styles.BaseButton, {
  variants: {
    variant: {
      primary: styles.primary,
      inverted: styles.inverted,
      destructive: styles.destructive,
      outline: styles.outline,
      secondary: styles.secondary,
      ghost: styles.ghost,
      link: styles.link,
    },
    size: {
      default: styles['size-default'],
      xs: styles['size-xs'],
      sm: styles['size-sm'],
      md: styles['size-md'],
      lg: styles['size-lg'],
      xl: styles['size-xl'],
      wide: styles['size-wide'],
      xwide: styles['size-xwide'],
    },
    fullWidth: {
      true: 'w-full',
      false: 'w-auto',
    },
    iconOnly: {
      true: styles['icon-only'],
      false: '',
    },
  },
  defaultVariants: {
    variant: 'primary',
    size: 'default',
    fullWidth: false,
    iconOnly: false,
  },
});

export interface BaseButtonProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof baseButtonVariants> {
  asChild?: boolean;
}

const BaseButton = React.forwardRef<HTMLButtonElement, BaseButtonProps>(
  (
    {
      className,
      iconOnly = false,
      variant = 'primary',
      size = 'default',
      fullWidth = false,
      asChild = false,
      ...props
    },
    ref,
  ) => {
    const Comp = asChild ? Slot : 'button';
    return (
      <Comp
        className={cn(
          styles.BaseButton,
          baseButtonVariants({ variant, fullWidth, size, iconOnly, className }),
        )}
        ref={ref}
        {...props}
      />
    );
  },
);
BaseButton.displayName = 'Button';

export { BaseButton, baseButtonVariants };
