import * as React from 'react'
import * as TogglePrimitive from '@radix-ui/react-toggle'
import tw, { TwStyle } from 'twin.macro'

const PRIMARY_STYLE = tw`
  inline-flex
  items-center
  justify-center
  rounded-md
  text-sm
  font-medium
  transition-colors
  data-[state=on]:bg-slate-200
  dark:hover:bg-slate-800
  dark:data-[state=on]:bg-slate-700
  focus:outline-none
  dark:text-slate-100
  focus:ring-2
  focus:ring-slate-400
  focus:ring-offset-2
  disabled:pointer-events-none
  disabled:opacity-50
  dark:focus:ring-offset-slate-900
  hover:bg-slate-100
  dark:hover:text-slate-100
  dark:data-[state=on]:text-slate-100
`

type VariantType = 'default' | 'outline'
type SizeType = 'default' | 'sm' | 'lg'

const VARIANT_MAP = {
  default: tw`bg-transparent`,
  outline: tw`bg-transparent border border-slate-200 hover:bg-slate-100 dark:border-slate-700`,
} satisfies Record<VariantType, TwStyle>

const SIZE_MAP = {
  default: tw`h-10 px-3`,
  sm: tw`h-9 px-2.5`,
  lg: tw`h-11 px-5`,
} satisfies Record<SizeType, TwStyle>

interface ToggleProps
  extends React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> {
  variant?: VariantType
  size?: SizeType
}

const Toggle = React.forwardRef<
  React.ElementRef<typeof TogglePrimitive.Root>,
  ToggleProps
>(({ variant = 'default', size = 'default', ...props }, ref) => (
  <TogglePrimitive.Root
    ref={ref}
    css={[PRIMARY_STYLE, VARIANT_MAP[variant], SIZE_MAP[size]]}
    {...props}
  />
))

Toggle.displayName = TogglePrimitive.Root.displayName

const _Toggle = Toggle
export { _Toggle as Toggle, VARIANT_MAP, SIZE_MAP }
export type { VariantType, SizeType, ToggleProps }
