import React, { useEffect } from "react";

const RadioField = React.forwardRef(
    ({ label, options, value, onChangeInput, errorMsg, containerClass, ...restProps }, ref) => {
        useEffect(() => {
            if (value !== "" && typeof value !== "object" && options.find(opt => value == opt.value)) {
                let newVal = getValueObj(value);
                onChangeInput(newVal, false); //selecting the value that was set before options were populated
            }
        }, [value]);

        const getValueObj = _value => options.find(v => v.value == _value);

        const handleRadioChange = e => {
            let newVal = e.target.value;
            if (newVal === "true") newVal = true;
            if (newVal === "false") newVal = false;
            let valObj = getValueObj(newVal);
            onChangeInput(valObj);
        };

        return (
            <div className={`input-field-sec radio-group ${errorMsg ? "error-field" : ""} ${containerClass || ""}`}>
                {options.map((option, i) => (
                    <React.Fragment key={i}>
                        <input
                            ref={ref}
                            type="radio"
                            id={option.label}
                            className="Custom-BeneCheckbox"
                            value={option.value}
                            checked={value.value == option.value}
                            onChange={handleRadioChange}
                            {...restProps}
                        />
                        <label className={`${value.value == option.value ? "checked" : ""}`}>
                            <span>{option.label}</span>
                        </label>
                    </React.Fragment>
                ))}
                {errorMsg && <span className="helperTextError">{errorMsg}</span>}
            </div>
        );
    }
);

export default RadioField;
