import "./index.css";

import clsx from "clsx";
import { forwardRef, useId } from "react";

export type ValueToggleOption = {
	value: string | number;
	label?: React.ReactNode;
	disabled?: boolean;
};

export type ValueToggleGroupProps = {
	options: ValueToggleOption[];
	value?: string | number;
	defaultValue?: string | number;
	onChange?: (value: string | number) => void;
	className?: string;
	name?: string;
	id?: string;
	style?: React.CSSProperties;
	orientation?: "horizontal" | "vertical";
};

export const ValueToggleGroup = forwardRef<HTMLFieldSetElement, ValueToggleGroupProps>(function ValueToggleGroup(
	{ options, value, defaultValue, onChange, className, name, id, style, orientation = "horizontal" },
	ref,
) {
	let randomId = useId();
	let groupName = name || `toggle-${id ?? randomId}`;
	let isControlled = value !== undefined;

	return (
		// oxlint-disable-next-line jsx-a11y/no-noninteractive-element-to-interactive-role -- legacy component
		<fieldset className={clsx("ObValueToggleGroup", orientation, className)} role="radiogroup" ref={ref} style={style}>
			{options.map((opt) => {
				return (
					<label key={opt.value} className={clsx("ObValueToggleOption", { disabled: opt.disabled })}>
						<input
							type="radio"
							name={groupName}
							value={opt.value}
							checked={isControlled ? value === opt.value : undefined}
							defaultChecked={!isControlled ? defaultValue === opt.value : undefined}
							onChange={() => onChange?.(opt.value)}
							disabled={opt.disabled}
						/>
						<span className="ObValueToggleLabel">{opt.label ?? opt.value}</span>
					</label>
				);
			})}
		</fieldset>
	);
});
