<template>
  <dialog ref="dialogRef" class="app-dialog" @close="unlockScroll(); $emit('close')">
    <form class="dialog-form" method="dialog" @submit.prevent="handleSave">
      <header>
        <h2>{{ isEdit ? '编辑文件夹' : '新建文件夹' }}</h2>
        <button type="button" aria-label="关闭" @click="closeDialog">×</button>
      </header>

      <div class="field-grid">
        <label class="field-span-2">
          <span>文件夹名称 <em>*</em></span>
          <input v-model="form.name" type="text" placeholder="请输入文件夹名称" required autofocus />
        </label>
        <label class="field-span-2">
          <span>描述</span>
          <input v-model="form.description" type="text" placeholder="请输入文件夹描述（可选）" />
        </label>
        <label>
          <span>排序权重</span>
          <input v-model.number="form.sortWeight" type="number" min="0" placeholder="数字越小越靠前，默认 0" />
        </label>
      </div>

      <footer>
        <span></span>
        <span></span>
        <button type="button" class="secondary" @click="closeDialog">取消</button>
        <button type="submit" :disabled="!form.name?.trim()">{{ isEdit ? '保存' : '创建' }}</button>
      </footer>
    </form>
  </dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { lockScroll, unlockScroll } from '../utils/scrollLock'

const props = defineProps({
  open: Boolean,
  folder: {
    type: Object,
    default: null,
  },
})

const emit = defineEmits(['close', 'save'])

const dialogRef = ref(null)
const isEdit = ref(false)

const form = ref({
  name: '',
  description: '',
  sortWeight: 0,
})

watch(
  () => props.open,
  (value) => {
    if (!dialogRef.value) return
    if (value && !dialogRef.value.open) {
      // 打开时初始化表单
      if (props.folder) {
        isEdit.value = true
        form.value = {
          name: props.folder.title || '',
          description: props.folder.description || '',
          sortWeight: props.folder.sortWeight ?? 0,
        }
      } else {
        isEdit.value = false
        form.value = {
          name: '',
          description: '',
          sortWeight: 0,
        }
      }
      dialogRef.value.showModal()
      lockScroll()
    }
    if (!value && dialogRef.value.open) {
      dialogRef.value.close()
      unlockScroll()
    }
  },
)

function closeDialog() {
  dialogRef.value?.close()
}

function handleSave() {
  if (!form.value.name?.trim()) return
  emit('save', {
    name: form.value.name.trim(),
    description: form.value.description?.trim() || '',
    sortWeight: Number(form.value.sortWeight) || 0,
  })
  closeDialog()
}
</script>
