import React, { FC, memo, useRef } from 'react';
import { cn }                      from '../../util/bem';
import { FormSizesType, SizeType } from '../../util/global-props';
import './radio-group.component.scss';

export type RadioGroupPropsType = {
    className?: string;
    label?: React.ReactNode;
    disabled?: boolean;
    value: string;
    autoFocus?: boolean;
    height?: FormSizesType;
    margin?: SizeType;
    size?: 'sm' | 'md' | 'lg';
    style?: React.CSSProperties;
    viewType: 'block' | 'radio';
    theme?: 'primary' | 'primary-green' | 'primary-white' | 'secondary' | 'dark' | 'transparent' | 'alert';

    flex?: number;

    onChange?: (val: string) => void;

    tabIndex?: number;
    children?: React.ReactNode;
}

const classNames = cn('radio-group');

export const RadioGroup: FC<RadioGroupPropsType> = memo((props) => {
    const node = useRef<HTMLInputElement>(null);


    const handleClick = (val: string) => {
        if (props.onChange) {
            props.onChange(val);
        }
    };

    return (
        <div
            className={ classNames({
                height:   props.height,
                margin:   props.margin,
                label:    !!props.label,
                size:     props.size,
                viewType: props.viewType
            }, null, props.className) }

            ref={ node }
            style={ props.style }
        >
            {
                React.Children.map(props.children, (child) => (
                    React.isValidElement(child)
                        ? React.cloneElement(child, {
                            ...child.props,
                            viewType: props.viewType,
                            checked:  props.value === child.props.value,
                            theme:    props.theme,
                            onChange: (val: string) => {
                                handleClick(val);
                            },
                            onClick: (val: string) => handleClick(val)
                        })
                        : null))
            }
        </div>
    );
});


RadioGroup.defaultProps = {
    disabled:  false,
    autoFocus: false,
    size:      'sm'
};
