// src/utils/toast.js
import { createApp } from 'vue'
import ErrorModal from '../components/Toast.vue'
import i18n from '@/locales/i18n'

class ErrorModalManager {
  constructor() {
    this.instances = []
  }

  // 显示错误弹框
  show(message, options = {}) {
    const container = document.createElement('div')
    document.body.appendChild(container)

    const app = createApp(ErrorModal, {
      message,
      ...options,
      onConfirm: () => {
        if (options.onConfirm) {
          options.onConfirm()
        }
        this.cleanup(app, container)
      },
      onClose: () => {
        if (options.onClose) {
          options.onClose()
        }
        this.cleanup(app, container)
      },
    })

    // 注入 i18n 实例以支持多语言
    app.use(i18n)

    const instance = app.mount(container)
    this.instances.push(app)

    return {
      close: () => instance.close(),
      instance,
    }
  }

  // 清理DOM和实例
  cleanup(app, container) {
    setTimeout(() => {
      if (container && container.parentNode) {
        container.parentNode.removeChild(container)
      }
      app.unmount()

      // 从实例列表中移除
      const index = this.instances.indexOf(app)
      if (index > -1) {
        this.instances.splice(index, 1)
      }
    }, 100)
  }

  // 关闭所有弹框
  closeAll() {
    this.instances.forEach((app) => {
      const instance = app._instance
      if (instance && instance.exposed && instance.exposed.close) {
        instance.exposed.close()
      }
    })
    this.instances = []
  }
}

// 创建全局实例
export const errorModal = new ErrorModalManager()

// 快捷方法 - 替代alert
export const showError = (message, title = null) => {
  // 如果没有提供标题，则使用国际化文本
  const finalTitle = title || i18n.global.t('error')
  return errorModal.show(message, { title: finalTitle, type: 'error' })
}

// 信息提示
export const showInfo = (message, title = null) => {
  const finalTitle = title || i18n.global.t('information')
  return errorModal.show(message, { title: finalTitle, type: 'info' })
}

// 成功提示
export const showSuccess = (message, title = null) => {
  const finalTitle = title || i18n.global.t('success')
  return errorModal.show(message, { title: finalTitle, type: 'success' })
}

// 警告提示
export const showWarning = (message, title = null) => {
  const finalTitle = title || i18n.global.t('warning')
  return errorModal.show(message, { title: finalTitle, type: 'warning' })
}

// 通用提示方法
export const showToast = (message, options = {}) => {
  const defaultOptions = {
    title: i18n.global.t('information'),
    type: 'info',
    duration: 3000, // 自动关闭时间
    ...options,
  }
  return errorModal.show(message, defaultOptions)
}

export const showMessage = (message, options = {}) => {
  const defaultOptions = {
    confirmText: i18n.global.t('ok') || 'OK',
    type: 'simple',
    ...options,
  }
  return errorModal.show(message, defaultOptions)
}

// 错误处理的专用方法
export const handleError = (error) => {
  let message = i18n.global.t('unknown_error') || 'An unknown error occurred'
  let title = i18n.global.t('error') || 'Error'

  if (error.errorCode === 1083) {
    title = i18n.global.t('service_unavailable') || 'Service Unavailable'
    message = i18n.global.t('exchange_not_available') || 'Exchange function is not available'
  } else if (error.errorCode === 6010) {
    title = i18n.global.t('team_not_found') || 'Team Not Found'
    message = i18n.global.t('team_not_exist') || 'The team does not exist or has been disbanded'
  } else if (error.message && error.message.includes('HTTP Error: 406')) {
    title = i18n.global.t('request_not_acceptable') || 'Request Not Acceptable'
    message = i18n.global.t('something_went_wrong') || 'Something went wrong, please retry.'
  } else if (error.errorMsg) {
    // 优先使用 errorMsg
    message = error.errorMsg
    if (error.errorCodeName) {
      title = error.errorCodeName
        .replace(/_/g, ' ')
        .toLowerCase()
        .replace(/\b\w/g, (l) => l.toUpperCase())
    }
  } else if (error.message) {
    message = error.message
  }

  return errorModal.show(message, { title, type: 'error' })
}

// 确认对话框
export const showConfirm = (message, title = null) => {
  const finalTitle = title || i18n.global.t('confirm')
  return new Promise((resolve) => {
    errorModal.show(message, {
      title: finalTitle,
      confirmText: i18n.global.t('ok') || 'Confirm',
      onConfirm: () => resolve(true),
      onClose: () => resolve(false),
    })
  })
}

export default errorModal
