import { onBeforeUnmount, onMounted, ref } from "vue";

export const useFocusOut = () => {
  const active = ref<Boolean>(false);
  const element = ref<Element | HTMLElement | null>(null);
  const focusOutElement = ref<string | null>(null);
  const focusElement = ref<any>(null);

  onMounted((): void => {
    if (!getCurrentElement()) {
      alert("Provide Focus Out Callback");
    }
    element.value = getCurrentElement();
    setFocusOutHandler();
  });

  onBeforeUnmount((): void => {
    unsetFocusOutHandler();
  });

  const getCurrentElement = (): any => {
    if (focusOutElement.value) {
      if (focusElement.value.$el) {
        return focusElement.value.$el.querySelector(focusOutElement.value);
      }
      return focusElement.value.querySelector(focusOutElement.value);
    }
    return focusElement.value.$el;
  };

  const setFocusOutHandler = (): void => {
    let element = getCurrentElement();
    element.addEventListener("focusout", focusOutHandler);
  };

  const unsetFocusOutHandler = (): void => {
    let element = getCurrentElement();
    element.removeEventListener("focusout", focusOutHandler);
  };

  const focusOutHandler = (event: any): void => {
    if (element.value) {
      const leavingParent = !element.value.contains(event.relatedTarget);

      if (leavingParent) {
        active.value = false;
      }
    }
  };

  return {
    focusOutHandler,
    unsetFocusOutHandler,
    setFocusOutHandler,
    getCurrentElement,
    element,
    focusOutElement,
    active,
    focusElement,
  };
};
