import React, { forwardRef } from 'react';
import * as RadixRadioGroup from '@radix-ui/react-radio-group';

import { theme, styled } from '../../stitches.config';

import { InputOptions } from '../../utility';
import { useValue } from '../../hooks';

export interface RadioProps
    extends InputOptions<string>,
        Omit<
            React.ComponentPropsWithRef<'div'>,
            'value' | 'defaultValue' | 'defaultChecked' | 'onChange' | 'dir'
        > {
    /** Orientation of the component */
    orientation?: 'horizontal' | 'vertical';
}

const StyledRadioRoot = styled(RadixRadioGroup.Root, {
    display: 'flex',
    flexWrap: 'wrap',
    gap: theme.space['2'],
    '&[data-orientation=horizontal]': {
        flexDirection: 'row',
    },
    '&[data-orientation=vertical]': {
        flexDirection: 'column',
    },
});

/**
 * Radio component
 */
export const Radio = forwardRef<HTMLDivElement, RadioProps>(
    (props, ref): JSX.Element => {
        const {
            id,
            children,
            value,
            defaultValue,
            onChange = () => null,
            orientation = 'vertical',
            ...otherProps
        } = props;

        // manage the internal value
        const [internalValue, setInternalValue] = useValue({
            initialValue: '',
            value: value,
            defaultValue: defaultValue,
            onChange: onChange,
        });

        return (
            <StyledRadioRoot
                ref={ref}
                id={id}
                value={internalValue}
                onValueChange={setInternalValue}
                loop={true}
                orientation={orientation}
                {...otherProps}
            >
                {children}
            </StyledRadioRoot>
        );
    },
);

Radio.displayName = 'Radio';
