<template>
  <dialog ref="dialogRef" class="modal" :aria-labelledby="titleId" @close="onClose">
    <div class="modal-box">
      <h2 :id="titleId" class="font-bold text-lg mb-2">{{ title }}</h2>
      <p>{{ message }}</p>
      <div class="modal-action">
        <form method="dialog">
          <button type="button" class="btn" @click="cancel">Cancel</button>
        </form>
        <button
          type="button"
          :class="danger ? 'btn btn-error' : 'btn btn-primary'"
          :disabled="loading"
          @click="confirm"
        >
          <span v-if="loading" class="loading loading-spinner loading-sm" />
          <span v-else>{{ confirmLabel }}</span>
        </button>
      </div>
    </div>
    <form method="dialog" class="modal-backdrop">
      <button type="button" aria-label="Close" @click="cancel">Close</button>
    </form>
  </dialog>
</template>

<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    modelValue: boolean
    title: string
    message: string
    confirmLabel?: string
    danger?: boolean
    loading?: boolean
  }>(),
  { confirmLabel: 'Confirm', danger: false, loading: false }
)

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  confirm: []
}>()

const titleId = computed(() => `confirm-modal-title-${Math.random().toString(36).slice(2)}`)
const dialogRef = ref<HTMLDialogElement | null>(null)

watch(
  () => props.modelValue,
  (open) => {
    if (open) {
      dialogRef.value?.showModal()
    } else {
      dialogRef.value?.close()
    }
  }
)

function cancel() {
  dialogRef.value?.close()
  emit('update:modelValue', false)
}

function onClose() {
  emit('update:modelValue', false)
}

function confirm() {
  emit('confirm')
}
</script>
