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

const toggleVariants = cva('', {
  variants: {
    size: {
      default:
        'h-[30px] w-[52px] [&_span]:size-6 [&_span]:data-[state=checked]:translate-x-6 [&_span]:data-[state=unchecked]:translate-x-[2px]',
      sm: 'h-[22px] w-[40px] [&_span]:size-4 [&_span]:data-[state=checked]:translate-x-[20px] [&_span]:data-[state=unchecked]:translate-x-[2px]',
    },
  },
  defaultVariants: {
    size: 'default',
  },
})

export interface ToggleProps
  extends React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root>,
    VariantProps<typeof toggleVariants> {
  ref?: React.Ref<React.ElementRef<typeof TogglePrimitive.Root>>
}

const Toggle = ({ className, size, ref, ...props }: ToggleProps) => (
  <TogglePrimitive.Root
    ref={ref}
    className={cn(
      'peer inline-flex shrink-0 items-center rounded-full border border-transparent outline-none transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-toggle-on data-[state=unchecked]:bg-toggle-off',
      toggleVariants({ size, className }),
    )}
    {...props}
  >
    <TogglePrimitive.Thumb
      className={cn(
        'pointer-events-none block rounded-full bg-background-alt ring-0 transition-transform dark:data-[state=checked]:bg-background dark:data-[state=unchecked]:bg-foreground',
      )}
    />
  </TogglePrimitive.Root>
)
Toggle.displayName = 'Toggle'

export { Toggle }
