import * as React from 'react'
import * as RSwitch from '@radix-ui/react-switch'
import { cn } from './cva'
import { useFieldControl } from './Field'

export interface SwitchProps {
  checked?: boolean
  defaultChecked?: boolean
  onCheckedChange?(v: boolean): void
  disabled?: boolean
  id?: string
  'aria-label'?: string
  'aria-describedby'?: string
  className?: string
}

export const Switch = React.forwardRef<HTMLButtonElement, SwitchProps>(
  ({ id, className, ...props }, ref) => {
    const field = useFieldControl()
    return (
      <RSwitch.Root
        ref={ref}
        id={id ?? field?.id}
        aria-describedby={props['aria-describedby'] ?? field?.describedBy}
        className={cn(
          'inline-flex h-5 w-9 items-center rounded-full border border-border bg-surface px-0.5 transition-colors disabled:opacity-50 disabled:cursor-not-allowed data-[state=checked]:bg-accent',
          className,
        )}
        {...props}
      >
        <RSwitch.Thumb className="block h-4 w-4 rounded-full bg-fg transition-transform data-[state=checked]:translate-x-4" />
      </RSwitch.Root>
    )
  },
)
Switch.displayName = 'Switch'
