import React, { InputHTMLAttributes, useImperativeHandle, useRef } from 'react';
import * as _ from 'lodash';
import { IRadioProps } from './Radio.interface';
import Style from './Radio.style';
import { RadioCore } from './RadioCore';

export const RadioPure = React.forwardRef<InputHTMLAttributes<any>, IRadioProps>(function RadioPure(
   { value, onChange, options, title, defaultValue, error, color, rightRadio, as, ...rest },
   inputRef: any,
) {
   const inputRefs = useRef<any>([]);
   useImperativeHandle(inputRef, () => inputRefs.current, []);

   return (
      <Style color={color}>
         {options.map((option, index) => {
            return (
               <div className="radio-container" key={`radio-${index}`}>
                  <label className="radio-container radio-label clean">
                     <input
                        ref={(elRef) => {
                           inputRefs.current[index] = elRef;
                        }}
                        type="radio"
                        disabled={option.disabled}
                        checked={value !== undefined ? _.isEqual(option.value, value) : undefined} // remove uncontrolled if value is defined
                        defaultChecked={value === undefined ? _.isEqual(defaultValue, option.value) : undefined} // remove uncontrolled if value is defined
                        {...rest}
                        onChange={() => {
                           if (onChange) {
                              onChange(option.value);
                           }
                        }}
                        data-testid={`radio-${index}`}
                     />
                     <span
                        className={`radio ${error && 'has-error'} ${option.disabled && 'disabled'} ${
                           rightRadio && 'right'
                        }`}
                        data-testid={`input-radio-circle-${index}`}
                     />
                     <span className={`title ${option.disabled && 'disabled'} ${rightRadio && 'right'}`}>
                        {option.name}
                     </span>
                  </label>
               </div>
            );
         })}
         {error && (
            <div className="error-input" data-testid="input-error">
               {error}
            </div>
         )}
      </Style>
   );
});

export const Radio = React.forwardRef<InputHTMLAttributes<any>, IRadioProps>(function Checkbox(props, inputRef: any) {
   const ref = useRef();
   useImperativeHandle(inputRef, () => ref.current, []);

   return <RadioCore {...props} ref={ref} as={RadioPure} />;
});
