import { createApp, nextTick } from 'vue'
import MessagePopup from './index.vue'

const message = {
  success(options, duration = 2000) {
    if (process.client) {
      if (typeof options === 'string') {
        this.show({ type: 'success', message: options, duration })
      } else {
        this.show({ 
          type: 'success',
          ...options,
          duration 
        })
      }
    }
  },
  error(options, duration = 2000) {
    if (process.client) {
      if (typeof options === 'string') {
        this.show({ type: 'error', message: options, duration })
      } else {
        this.show({ 
          type: 'error',
          ...options,
          duration 
        })
      }
    }
  },
  info(options, duration = 2000) {
    if (process.client) {
      if (typeof options === 'string') {
        this.show({ type: 'info', message: options, duration })
      } else {
        this.show({
          type: 'error',
          ...options,
          duration
        })
      }
    }
  },
  warning(options, duration = 2000) {
    if (process.client) {
      if (typeof options === 'string') {
        this.show({ type: 'warning', message: options, duration })
      } else {

        this.show({ 
          type: 'warning',
          ...options,
          duration 
        })
      }
    }
  },
  show(options) {
    if (!process.client) return
    
    const container = document.createElement('div')
    document.body.appendChild(container)
    
    const app = createApp(MessagePopup, {
      onAfterLeave: () => {
        app.unmount()
        document.body.removeChild(container)
      }
    })
    
    const instance = app.mount(container)
    nextTick(() => {
      instance.showMessage?.(options)
    })
  }
}

export { message }