import { ref, unref, watch } from 'vue';
import { tryOnUnmounted } from '@vueuse/core';
import type { ModalMethods, UseModalReturnType, modalProps } from '../types';
export function useModal(props: modalProps): UseModalReturnType {
  const modalRef = ref<Nullable<ModalMethods>>(null);

  const getInstance = () => {
    const instance = unref(modalRef.value);
    if (!instance) {
      console.error('useModal instance is undefined!');
    }
    return instance;
  };

  const register = (modalInstance: ModalMethods) => {
    tryOnUnmounted(() => {
      modalRef.value = null;
    });
    modalRef.value = modalInstance;

    watch(
      () => props,
      () => {
        if (props) {
          modalInstance.setModalProps(props);
        }
      },
      {
        immediate: true,
        deep: true
      }
    );
  };

  const methods: ModalMethods = {
    setModalLoading(status) {
      getInstance()?.setModalLoading(status);
    },
    setModalProps: (newProps: modalProps): void => {
      getInstance()?.setModalProps(newProps);
    },
    openModal: (record?: Recordable) => {
      getInstance()?.openModal(record);
    },
    closeModal: () => {
      getInstance()?.closeModal();
    },
    setSubLoading: status => {
      getInstance()?.setSubLoading(status);
    }
  };

  return [register, methods];
}
