import { ref } from 'vue'

export function useModal() {
  const showModal = ref(false)
  const modalConfig = ref({
    title: 'Hinweis',
    message: '',
    type: 'alert',
    confirmText: 'OK',
    cancelText: 'Abbrechen'
  })
  const resolvePromise = ref(null)

  const alert = (message, title = 'Hinweis') => {
    return new Promise((resolve) => {
      modalConfig.value = {
        title,
        message,
        type: 'alert',
        confirmText: 'OK',
        cancelText: 'Abbrechen'
      }
      showModal.value = true
      resolvePromise.value = resolve
    })
  }

  const confirm = (message, title = 'Bestätigung') => {
    return new Promise((resolve) => {
      modalConfig.value = {
        title,
        message,
        type: 'confirm',
        confirmText: 'Ja',
        cancelText: 'Abbrechen'
      }
      showModal.value = true
      resolvePromise.value = resolve
    })
  }

  const onConfirm = () => {
    showModal.value = false
    if (resolvePromise.value) {
      resolvePromise.value(true)
      resolvePromise.value = null
    }
  }

  const onCancel = () => {
    showModal.value = false
    if (resolvePromise.value) {
      resolvePromise.value(false)
      resolvePromise.value = null
    }
  }

  return {
    showModal,
    modalConfig,
    alert,
    confirm,
    onConfirm,
    onCancel
  }
}

