import isFunction from 'lodash/isFunction';
import { ToastPlugin } from '../../../vendor/bootstrap-vue/src/components/toast/index';
import CloseButton from '../../shared_components/close_button/close_button';

/* eslint-disable import/no-default-export */
const DEFAULT_OPTIONS = {
  autoHideDelay: 5000,
  toastClass: 'gl-toast',
  isStatus: true,
  toaster: 'b-toaster-bottom-left',
  appendToast: true
};
let toastsCount = 0;
function renderTitle(h, toast, options) {
  const nodes = [h(CloseButton, {
    class: ['gl-toast-close-button'],
    on: {
      click: toast.hide
    }
  })];
  if (options.action) {
    const {
      onClick,
      text,
      href
    } = options.action;
    nodes.unshift(h('a', {
      attrs: {
        role: href ? undefined : 'button',
        href
      },
      class: ['gl-toast-action'],
      on: {
        click: e => onClick(e, toast)
      }
    }, text));
  }
  return nodes;
}
function showToast(message) {
  let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  // eslint-disable-next-line @gitlab/tailwind-no-interpolation -- Not a CSS utility
  const id = `gl-toast-${toastsCount}`;
  toastsCount += 1;
  const hide = () => {
    this.$bvToast.hide(id);
  };
  const toast = {
    id,
    hide
  };
  if (isFunction(options.onComplete)) {
    const toastHiddenCallback = e => {
      if (e.componentId === id) {
        this.$root.$off('bv::toast:hidden', toastHiddenCallback);
        options.onComplete(e);
      }
    };
    this.$root.$on('bv::toast:hidden', toastHiddenCallback);
  }
  const updatedAutoHideDelay = !Number.isNaN(options === null || options === void 0 ? void 0 : options.autoHideDelay) ? {
    autoHideDelay: options.autoHideDelay
  } : null;
  this.$bvToast.toast(message, {
    ...DEFAULT_OPTIONS,
    ...updatedAutoHideDelay,
    id,
    title: renderTitle(this.$createElement, toast, options)
  });
  return toast;
}

/**
 * Note: This is not a typical Vue component and needs to be registered before instantiating a Vue app.
 * Once registered, the toast will be globally available throughout your app.
 *
 * See https://design.gitlab.com/storybook for detailed documentation.
 */
var toast = {
  install(Vue) {
    Vue.use(ToastPlugin);
    Vue.mixin({
      beforeCreate() {
        if (this.$toast) {
          return;
        }
        this.$toast = {
          show: showToast.bind(this)
        };
      }
    });
  }
};

export { toast as default };
