import { jsx, jsxs } from 'react/jsx-runtime';
import React__default, { useId, useState, useMemo } from 'react';
import { cn } from '../../../utils/cn.js';
import { radioTheme } from './Radio.theme.js';
import { formLabelTheme } from '../FormLabel/FormLabel.theme.js';
import { RadioGroupContext } from './RadioContext.js';

const RadioGroup = React__default.forwardRef(({ value: controlledValue, defaultValue, onChange, name, size = "md", state = "default", orientation = "vertical", label, description, error, required, className, children, ...props }, ref) => {
    const autoId = useId();
    const groupName = name !== null && name !== void 0 ? name : `radio-group-${autoId}`;
    const labelId = `${autoId}-label`;
    const descriptionId = `${autoId}-desc`;
    const errorId = `${autoId}-error`;
    // Controlled vs uncontrolled
    const isControlled = controlledValue !== undefined;
    const [internalValue, setInternalValue] = useState(defaultValue);
    const currentValue = isControlled ? controlledValue : internalValue;
    const handleChange = (itemValue) => {
        if (!isControlled) {
            setInternalValue(itemValue);
        }
        onChange === null || onChange === void 0 ? void 0 : onChange(itemValue);
    };
    const contextValue = useMemo(() => ({
        name: groupName,
        value: currentValue,
        onChange: handleChange,
        size,
        state,
    }), [groupName, currentValue, size, state]);
    const labelState = error ? "invalid" : state === "disabled" ? "disabled" : "default";
    return (jsx(RadioGroupContext.Provider, { value: contextValue, children: jsxs("fieldset", { ref: ref, role: "radiogroup", "aria-labelledby": label ? labelId : undefined, "aria-describedby": description ? descriptionId : undefined, "aria-required": required || undefined, "aria-invalid": error ? true : undefined, "aria-errormessage": error ? errorId : undefined, className: cn("border-0 p-0 m-0", radioTheme.groupStyle, className), ...props, children: [label && (typeof label === 'string' ? (jsxs("legend", { id: labelId, className: cn(formLabelTheme.baseStyle, formLabelTheme.stateStyles[labelState]), children: [label, required && (jsx("span", { className: formLabelTheme.requiredIndicatorStyle, children: "*" }))] })) : label), description && (typeof description === 'string' ? (jsx("p", { id: descriptionId, className: radioTheme.groupDescriptionStyle, children: description })) : description), jsx("div", { className: cn(radioTheme.groupItemsStyle, orientation === "horizontal" && radioTheme.groupHorizontalStyle), children: children }), error && (typeof error === 'string' ? (jsx("p", { id: errorId, role: "alert", className: radioTheme.groupErrorStyle, children: error })) : error)] }) }));
});
RadioGroup.displayName = "Radio.Group";

export { RadioGroup };
