import * as TogglePrimitive from '@radix-ui/react-toggle';
import { type VariantProps, cva } from 'class-variance-authority';
import * as React from 'react';

import { Slot } from '@radix-ui/react-slot';
import { cn } from '../..';

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

const baseToggleVariants = cva(styles.BaseToggle, {
  variants: {
    variant: {
      default: styles.default,
      outline: styles.outline,
    },
    size: {
      default: styles['size-default'],
      sm: styles['size-sm'],
      lg: styles['size-lg'],
    },
  },
  defaultVariants: {
    variant: 'default',
    size: 'default',
  },
});

const Toggle = React.forwardRef<
  React.ElementRef<typeof TogglePrimitive.Root>,
  React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> &
    VariantProps<typeof baseToggleVariants>
>(({ className, variant, size, ...props }, ref) => (
  <TogglePrimitive.Root
    ref={ref}
    className={cn(baseToggleVariants({ variant, size, className }))}
    {...props}
  />
));

export type BaseToggleProps = TogglePrimitive.ToggleProps &
  VariantProps<typeof baseToggleVariants> & {
    asChild?: boolean;
  };

const BaseToggle = React.forwardRef<HTMLButtonElement, BaseToggleProps>(
  ({ className, variant, size, asChild = false, ...props }, ref) => {
    const Comp = asChild ? Slot : Toggle;
    return (
      <Comp
        className={cn(
          styles.BaseToggle,
          baseToggleVariants({ variant, size, className }),
        )}
        ref={ref}
        {...props}
      />
    );
  },
);

BaseToggle.displayName = TogglePrimitive.Root.displayName;

export { BaseToggle, baseToggleVariants };
