import {ForwardedRef, useImperativeHandle, useRef, useState} from 'react';
import {TextInput, FocusEvent, BlurEvent} from 'react-native';

interface Params {
  ref?: ForwardedRef<TextInput>;
  onFocus?: (e: FocusEvent) => void;
  onBlur?: (e: BlurEvent) => void;
  onChangeText?: (value: string) => void;
}

export const useInputRef = ({ref, onFocus, onBlur, onChangeText}: Params) => {
  const [focused, setFocused] = useState(false);
  const inputRef = useRef<Nullable<TextInput>>(null);

  useImperativeHandle(ref, () => inputRef.current as TextInput, [inputRef]);

  const onInputFocus = (e: FocusEvent) => {
    setFocused(true);
    onFocus?.(e);
  };

  const onInputBlur = (e: BlurEvent) => {
    setFocused(false);
    onBlur?.(e);
  };

  const focusInput = () => inputRef.current?.focus();

  const clearInput = (withBlur: boolean = true) => {
    inputRef.current?.clear();
    onChangeText?.('');
    if (withBlur) {
      // Blur the input after a small delay to avoid the input being focused again
      setTimeout(() => {
        inputRef.current?.blur();
      }, 150);
    }
  };

  return {
    inputRef,
    focused,
    onInputFocus,
    onInputBlur,
    focusInput,
    clearInput,
  };
};
