import React, { useId, type HTMLAttributes } from 'react'
import classnames from 'classnames'
import { Label } from '~components/Label'
import { type OverrideClassName } from '~components/types/OverrideClassName'
import styles from './RadioGroup.module.css'

export type RadioGroupProps = OverrideClassName<HTMLAttributes<HTMLDivElement>> & {
  'children'?: React.ReactNode
  'labelText': string | React.ReactNode
  'labelId'?: string
  'noBottomMargin'?: boolean
  'reversed'?: boolean
  'data-testid'?: string
}

export const RadioGroup = ({
  children,
  'labelId': propsLabelId,
  labelText,
  noBottomMargin = false,
  reversed = false,
  classNameOverride,
  'data-testid': dataTestId,
  ...restProps
}: RadioGroupProps): JSX.Element => {
  const fallbackId = useId()
  const labelId = propsLabelId ?? fallbackId

  return (
    <div
      data-testid={dataTestId}
      className={classnames(
        styles.radioGroupContainer,
        classNameOverride,
        noBottomMargin && styles.noBottomMargin,
        reversed && styles.reversed,
      )}
      role="radiogroup"
      aria-labelledby={labelId}
      {...restProps}
    >
      <div className={styles.radioGroupLabel}>
        <Label
          id={labelId}
          data-testid={dataTestId && `${dataTestId}-field-label`}
          labelText={labelText}
          labelType="text"
          reversed={reversed}
        />
      </div>
      {children}
    </div>
  )
}

RadioGroup.displayName = 'RadioGroup'
