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

export const Checkbox: React.FunctionComponent<ICheckboxProps> = ({
   children,
   name,
   value = true,
   title,
   color,
   'data-cy': dataCy,
   ...rest
}) => {
   const inputRef = useRef(null);
   const { fieldName, registerField, defaultValue, error, clearError } = useField(name);
   const defaultChecked: any = _.isEqual(defaultValue, value);

   useEffect(() => {
      registerField({
         name: fieldName,
         ref: inputRef.current,
         path: 'value' as any,
         setValue: (ref: any, _value: any) => {
            ref.checked = _.isEqual(_value, value);
         },
         getValue: (ref: any) => {
            return ref.checked ? value : null;
         },
         clearValue(ref: any) {
            ref.checked = false;
         },
      });
   }, [fieldName, registerField, value]);

   return (
      <Style color={color}>
         <div className="checkbox-container clean">
            <label className="checkbox-container clean" data-cy={dataCy}>
               <input
                  type="checkbox"
                  ref={inputRef}
                  defaultChecked={defaultChecked}
                  {...rest}
                  onChange={() => {
                     if (error) clearError();
                     if (rest?.onChange) rest.onChange(inputRef.current.checked ? value : null);
                  }}
               />
               <span
                  className={`checkbox ${error && 'has-error'} ${rest.disabled && 'disabled'}`}
                  data-testid="input-checkbox-error"
               >
                  <i className="fas fa-check" />
               </span>
               <span className={`title ${rest.disabled && 'disabled'}`}>{title}</span>
            </label>
         </div>

         {error && (
            <div data-cy={`input-error.${rest['data-cy'] ?? ''}`} className="error-input" data-testid="input-error">
               {error}
            </div>
         )}
      </Style>
   );
};
