import React, { useRef, useEffect, useContext } from 'react';
import { useField } from '@unform/core';
import AppContext from '../../AppProvider/AppContext';
import { InputPure } from '../../Input/web';
import { IPropsSelect } from '../select.interface';
import Style from './Select.style';
import { SelectPure } from './SelectPure';

export const Select: React.FunctionComponent<IPropsSelect> = ({
   children,
   name,
   title,
   items,
   theme,
   as = SelectPure,
   ...rest
}: IPropsSelect) => {
   // Custom component
   const { pureComponents: { Select: SelectComponent = null } = {} } = useContext(AppContext);
   const Component = SelectComponent ?? as;

   const inputRef = useRef(null);
   const { fieldName, registerField, defaultValue, error } = useField(name);

   useEffect(() => {
      registerField({
         name: fieldName,
         ref: inputRef.current,
         path: 'value',
      });
   }, [fieldName, registerField, children]);

   return (
      <Style themeInput={theme}>
         <Component inputRef={inputRef} title={title} defaultValue={defaultValue} error={error} items={items} {...rest}>
            {children}
         </Component>
      </Style>
   );
};
