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

const segmentButtonVariants = cva(
  'inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-segment-button-active data-[state=on]:text-segment-button-active-foreground',
  {
    variants: {
      variant: {
        default:
          'bg-segment-button-background text-segment-button-foreground hover:bg-segment-button-background-hover',
        active:
          'bg-segment-button-active text-segment-button-active-foreground',
      },
      size: {
        default: 'h-12 px-3',
        sm: 'h-10 px-2.5',
        xs: 'h-8 px-5',
      },
    },
    defaultVariants: {
      variant: 'default',
      size: 'default',
    },
  },
)

type SegmentButtonProps = React.ComponentPropsWithoutRef<
  typeof TogglePrimitive.Root
> &
  VariantProps<typeof segmentButtonVariants> & {
    ref?: React.Ref<React.ElementRef<typeof TogglePrimitive.Root>>
  }

const SegmentButton = ({
  className,
  variant,
  size,
  ref,
  ...props
}: SegmentButtonProps) => (
  <TogglePrimitive.Root
    ref={ref}
    className={cn(segmentButtonVariants({ variant, size, className }))}
    {...props}
  />
)

SegmentButton.displayName = 'SegmentButton'

export { SegmentButton, segmentButtonVariants, type VariantProps }
