import * as React from "react"
import { RadioGroup as RadioGroupPrimitive } from "@base-ui/react/radio-group"
import { Radio } from "@base-ui/react/radio"
import { cn } from "../core/cn"

function RadioGroup({ className, ...props }: RadioGroupPrimitive.Props) {
  return (
    <RadioGroupPrimitive
      data-slot="radio-group"
      className={cn("grid gap-2", className)}
      {...props}
    />
  )
}

interface RadioGroupItemProps extends Radio.Root.Props {
  label?: string
  className?: string
  labelClassName?: string
}

function RadioGroupItem({ className, label, id, labelClassName, ...props }: RadioGroupItemProps) {
  const internalId = React.useId()
  const itemId = id ?? internalId

  return (
    <div className="flex items-center gap-2">
      <Radio.Root
        id={itemId}
        data-slot="radio-group-item"
        className={cn(
          "aspect-square size-4 rounded-full border border-input bg-transparent transition-colors outline-none",
          "focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50",
          "data-checked:border-primary",
          "disabled:pointer-events-none disabled:opacity-50",
          className
        )}
        {...props}
      >
        <Radio.Indicator
          data-slot="radio-group-indicator"
          className="flex items-center justify-center"
        >
          <span className="block size-2 rounded-full bg-primary" />
        </Radio.Indicator>
      </Radio.Root>
      {label && (
        <label
          htmlFor={itemId}
          data-slot="radio-group-label"
          className={cn("text-sm font-medium leading-none cursor-pointer select-none", labelClassName)}
        >
          {label}
        </label>
      )}
    </div>
  )
}

export { RadioGroup, RadioGroupItem }
export type { RadioGroupItemProps }
