import * as RadioGroupPrimitive from '@radix-ui/react-radio-group'

import { cva, type VariantProps } from 'class-variance-authority'
import * as React from 'react'

import { cn } from '@lib/utils'

function RadioGroup({
  className,
  __e2e_test_id__,
  ...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Root> & { __e2e_test_id__?: string }) {
  return (
    <RadioGroupPrimitive.Root
      data-test-id={__e2e_test_id__}
      data-slot="radio-group"
      className={cn('grid gap-3', className)}
      {...props}
    />
  )
}

const radioGroupVariants = cva(
  'cursor-pointer border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50',
  {
    variants: {
      circleVariant: {
        default: '',
        grayThick: 'aria-checked:border-muted-foreground aria-checked:border-2',
      },
      size: {
        default: 'size-4',
        sm: 'size-3.5',
      },
    },
    defaultVariants: {
      circleVariant: 'default',
      size: 'default',
    },
  },
)

type RadioGroupItemProps = React.ComponentProps<typeof RadioGroupPrimitive.Item> &
  VariantProps<typeof radioGroupVariants>

function RadioGroupItem({ className, circleVariant, size, ...props }: RadioGroupItemProps) {
  return (
    <RadioGroupPrimitive.Item
      data-slot="radio-group-item"
      className={cn(radioGroupVariants({ circleVariant, size, className }))}
      {...props}
    >
      <RadioGroupPrimitive.Indicator
        data-slot="radio-group-indicator"
        className="relative flex items-center justify-center"
      >
        <div
          className={`absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full ${
            circleVariant === 'grayThick' ? 'bg-muted-foreground' : 'bg-primary'
          }
          ${size === 'sm' ? 'size-2' : 'size-2.25'}`}
        />
      </RadioGroupPrimitive.Indicator>
    </RadioGroupPrimitive.Item>
  )
}

export { RadioGroup, RadioGroupItem }
