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

const rootVariants = cva(
  'peer inline-flex shrink-0 cursor-pointer items-center rounded-full overflow-hidden border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-border focus-visible:ring-offset-2 focus-visible:ring-offset-bg-base disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-fill-secondary',
  {
    variants: {
      size: { md: 'h-5 w-9', lg: 'h-6 w-11' },
    },
    defaultVariants: { size: 'md' },
  }
)

const thumbVariants = cva(
  'pointer-events-none block rounded-full bg-text-on-primary ring-0 transition-transform data-[state=unchecked]:translate-x-0',
  {
    variants: {
      size: {
        md: 'h-4 w-4 data-[state=checked]:translate-x-4',
        lg: 'h-5 w-5 data-[state=checked]:translate-x-4.5',
      },
    },
    defaultVariants: { size: 'md' },
  }
)

export interface SwitchProps
  extends Omit<React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>, 'onChange'>,
    VariantProps<typeof rootVariants> {
  size?: 'md' | 'lg'
}

const Switch = React.forwardRef<HTMLButtonElement, SwitchProps>(
  ({ className, size = 'md', disabled = false, ...rest }, ref) => (
    <SwitchPrimitives.Root
      ref={ref}
      className={cn(rootVariants({ size }), className)}
      disabled={disabled}
      {...rest}
    >
      <SwitchPrimitives.Thumb className={thumbVariants({ size })} />
    </SwitchPrimitives.Root>
  )
)
Switch.displayName = 'Switch'

export { Switch }
