import React, { useRef, useEffect, useState } from 'react';
import { View } from 'react-native';
import CheckBox from '@react-native-community/checkbox';
import { useField } from '@unform/core';
import * as _ from 'lodash';
import { useTheme } from 'styled-components';
import { Flex } from '../../Flex/native';
import { TextError } from '../../Input/native/Input.style';
import { Pressable } from '../../Pressable';
import { ICheckboxProps } from '../Checkbox.interface';
import { TitleText, CheckboxStyle } 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);
   const [isSelected, setSelection] = useState(defaultChecked);
   const theme: any = useTheme();

   useEffect(() => {
      registerField({
         name: fieldName,
         ref: inputRef,
         path: 'current' 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]);

   const setCheckBox = (v): void => {
      setSelection(v);
      inputRef.current = v;
   };

   return (
      <View>
         <CheckboxStyle onPress={() => setCheckBox(!isSelected)}>
            <CheckBox
               value={isSelected}
               onValueChange={setCheckBox}
               lineWidtH={8}
               tintColors={{ true: theme?.primary || '#222', false: '#a5a5a5' }}
            />

            {title && <TitleText>{title}</TitleText>}
         </CheckboxStyle>
         {!!error && <TextError testID="checkbox-error">{error}</TextError>}
      </View>
   );
};
