'use client'

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

const switchVariants = cva(
  'peer inline-flex shrink-0 items-center rounded-full border border-transparent transition-all duration-200',
  {
    variants: {
      size: {
        sm: 'h-4 w-8',
        lg: 'h-6 w-11',
      },
    },
    defaultVariants: {
      size: 'lg',
    },
  }
)

const thumbVariants = cva(
  'pointer-events-none block rounded-full transition-transform duration-200 shadow-sm',
  {
    variants: {
      size: {
        sm: 'size-3 data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0.5',
        lg: 'size-5 data-[state=checked]:translate-x-[1.375rem] data-[state=unchecked]:translate-x-0.5',
      },
    },
    defaultVariants: {
      size: 'lg',
    },
  }
)

interface SwitchProps
  extends React.ComponentProps<typeof SwitchPrimitive.Root>, VariantProps<typeof switchVariants> {
  loading?: boolean
}

function Switch({ className, loading, disabled, size, ...props }: SwitchProps) {
  return (
    <SwitchPrimitive.Root
      disabled={disabled || loading}
      data-loading={loading}
      className={cn(
        switchVariants({ size }),
        'data-[state=checked]:bg-primary-normal data-[state=unchecked]:bg-surface-element-normal',
        'hover:data-[state=checked]:bg-primary-hover hover:data-[state=unchecked]:bg-surface-element-hover',
        'active:data-[state=checked]:bg-primary-press active:data-[state=unchecked]:bg-surface-element-press',
        'disabled:data-[state=checked]:bg-primary-disabled disabled:data-[state=unchecked]:bg-surface-element-disabled',
        'disabled:cursor-not-allowed disabled:opacity-30',
        'focus-visible:ring-outline-normal focus-visible:ring-2 focus-visible:outline-none',
        'data-[loading=true]:animate-pulse',
        className
      )}
      {...props}
    >
      <SwitchPrimitive.Thumb
        className={cn(thumbVariants({ size }), 'bg-txt-primary-normal', 'disabled:opacity-50')}
      />
    </SwitchPrimitive.Root>
  )
}

export { Switch }
