import { onBeforeUpdate, onMounted, render, watch, nextTick } from 'vue';
import type { MyHTMLElement } from '../types';
import {
  EL_PICKER_PANEL_FOOTER,
  EXTRA_FOOTER_WRAPPER
} from '../utils/constants';
import { createExtraWrapper } from '../utils';

export const useExtraFooter = (
  elPopperEl: { value: MyHTMLElement },
  { props, slots }: any
) => {
  const extraFooter = props.renderExtraFooter
    ? props.renderExtraFooter
    : slots.renderExtraFooter;

  let wrapper: MyHTMLElement;

  // https://cn.vuejs.org/api/composition-api-setup#setup-context
  // 主要处理 slot v-if
  onBeforeUpdate(() => {
    if (extraFooter && wrapper) {
      // 如果当前已经有了 props 形式的的 renderExtraFooter，就不再继续判断 slot
      if (props.renderExtraFooter === undefined) {
        if (slots.renderExtraFooter === undefined) {
          // 📝 表示 slot 可能被删除 v-if=false，这里执行渲染空
          render(null, wrapper);
          wrapper.style.display = 'none';
        } else {
          render(<>{extraFooter?.()}</>, wrapper);
          wrapper.style.display = 'block';
        }
      }
    }
  });

  onMounted(async () => {
    await nextTick();
    wrapper = createExtraWrapper(elPopperEl.value, EXTRA_FOOTER_WRAPPER);
    if (extraFooter) {
      watch(
        () => extraFooter(),
        ExtraFooter => {
          if (wrapper) {
            if (ExtraFooter) {
              render(<>{ExtraFooter}</>, wrapper);
              wrapper.style.display = 'block';
            } else {
              render(null, wrapper);
              wrapper.style.display = 'none';
            }
          }
        },
        { immediate: true }
      );
    }
  });
};
