<template>
  <dialog ref="dialogRef" :open="modelValue" @cancel="handleCancel" @close="handleClose">
    <form method="dialog">
      <p>添加音乐库</p>
      <div class="dialog-body">
        <input v-model="name" type="text" placeholder="名称" />
        <input v-model="path" type="text" placeholder="路径" />
        <div class="dialog-buttons">
          <button :disabled="!validated" @click="confirm" value="confirm">确认</button>
          <button @click="close" value="cancel">取消</button>
        </div>
      </div>
    </form>
  </dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  modelValue: Boolean,
  title: String,
})

const name = ref()
const path = ref()

const emit = defineEmits(['update:modelValue', 'confirm'])

const dialogRef = ref(null)

// 监听外部值变化，同步到 dialog 元素
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      dialogRef.value?.showModal()
    } else {
      dialogRef.value?.close()
    }
  },
)

// 关闭时更新 v-model
const close = () => emit('update:modelValue', false)
const confirm = () => {
  emit('confirm', name.value, path.value)
  close()
}

const validated = computed(() => name.value && path.value)

// ESC 键触发 cancel 事件
const handleCancel = () => close()
// 调用 close() 时触发
const handleClose = () => emit('update:modelValue', false)
</script>

<style scoped>
.dialog-body {
  display: flex;
  flex-direction: column;
  gap: var(--size-3);
}

.dialog-buttons {
  display: flex;
  gap: var(--size-3);
  align-items: center;
  justify-content: center;
}
</style>
