'use client'

import * as RadioGroupPrimitive from '@radix-ui/react-radio-group'
import * as React from 'react'
import { cn } from '../../utils/cn'
import { ErrorMessage } from '../ErrorMessage'
import { typographyVariants } from '../Typography'
import { RadioGroupIndicator } from './RadioGroupIndicator'

type RadioGroupProps = React.ComponentPropsWithoutRef<
  typeof RadioGroupPrimitive.Root
> & {
  error?: string
  ref?: React.Ref<React.ElementRef<typeof RadioGroupPrimitive.Root>>
}

const RadioGroup = ({
  className,
  error,
  children,
  ref,
  ...props
}: RadioGroupProps) => (
  <div className="flex flex-col gap-2">
    <RadioGroupPrimitive.Root
      className={cn('grid gap-2', className)}
      {...props}
      ref={ref}
    >
      {children}
    </RadioGroupPrimitive.Root>
    {error && <ErrorMessage>{error}</ErrorMessage>}
  </div>
)
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName

type RadioGroupItemProps = React.ComponentPropsWithoutRef<
  typeof RadioGroupPrimitive.Item
> & {
  error?: boolean | string
  ref?: React.Ref<React.ElementRef<typeof RadioGroupPrimitive.Item>>
}

const RadioGroupItem = ({
  className,
  error = false,
  children,
  id,
  ref,
  ...props
}: RadioGroupItemProps) => {
  // Generate a unique ID if not provided
  const generatedId = React.useId()
  const radioId = id || generatedId

  return (
    <div className="flex flex-col gap-2">
      <div
        className={cn('flex items-center space-x-2', error && 'data-error')}
        data-error={error ? 'true' : undefined}
      >
        <RadioGroupPrimitive.Item
          ref={ref}
          id={radioId}
          className={cn(
            'group/radio peer relative flex h-4 w-4 shrink-0 items-center justify-center rounded-full border border-solid border-input-border bg-input hover:border-input-border-hover focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:border-input-border-disabled disabled:bg-input-disabled',
            error && 'border-input-border-error',
            className,
          )}
          {...props}
        >
          <RadioGroupPrimitive.Indicator className="flex items-center justify-center">
            <RadioGroupIndicator error={!!error} />
          </RadioGroupPrimitive.Indicator>
        </RadioGroupPrimitive.Item>
        {children && (
          <label
            htmlFor={radioId}
            className={cn(
              typographyVariants(),
              'cursor-pointer peer-disabled:cursor-not-allowed peer-disabled:text-input-muted-more-foreground',
            )}
          >
            {children}
          </label>
        )}
      </div>
      {typeof error === 'string' && <ErrorMessage>{error}</ErrorMessage>}
    </div>
  )
}
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName

export { RadioGroup, RadioGroupItem }
