import React, { useRef, useEffect } from 'react';
import { useField } from '@unform/core';
import * as _ from 'lodash';
import { IRadioProps } from '../Radio.interface';
import Style from './Radio.style';

export const Radio: React.FunctionComponent<IRadioProps> = ({
   children,
   name,
   value,
   options,
   title,
   color,
   'data-cy': dataCy,
   ...rest
}) => {
   const inputRefs = useRef([]);
   const { fieldName, registerField, defaultValue, error, clearError } = useField(name);

   useEffect(() => {
      registerField({
         name: fieldName,
         ref: inputRefs.current,
         path: 'value' as any,
         setValue: (refs: any, _value: any) => {
            const item = options.findIndex((option) => {
               return _.isEqual(option.id, _value);
            });

            if (item !== -1) {
               refs[item].checked = true;
            }
         },
         getValue: (refs: any) => {
            const checked = refs.find((ref) => ref.checked);

            return checked ? checked.value : null;
         },
         clearValue(ref: any) {
            ref.checked = false;
         },
      });
   }, [fieldName, registerField, options]);

   return (
      <Style color={color}>
         {options.map((option, index) => (
            <div className="checkbox-container" key={`${name}-radio-${index}`}>
               <label className="checkbox-container clean" data-cy={dataCy}>
                  <input
                     type="radio"
                     name={name}
                     value={option.id}
                     disabled={option.disabled}
                     ref={(elRef) => {
                        inputRefs.current[index] = elRef;
                     }}
                     defaultChecked={_.isEqual(defaultValue, option.id)}
                     {...rest}
                     onChange={() => !!error && clearError()}
                  />
                  <span
                     className={`checkbox ${error && 'has-error'} ${option.disabled && 'disabled'}`}
                     data-testid="input-radio-circle"
                  />
                  <span className={`title ${option.disabled && 'disabled'}`}>{option.label}</span>
               </label>
            </div>
         ))}
         {error && (
            <div data-cy={`input-error.${rest['data-cy'] ?? ''}`} className="error-input" data-testid="input-error">
               {error}
            </div>
         )}
      </Style>
   );
};
