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

      <div class="field-grid">
        <label v-if="!localRecord.id">
          <span>文件名</span>
          <input v-model.trim="localRecord.title" type="text" placeholder="请输入电影文件名，如 xxx.mp4" autofocus />
        </label>
        <template v-else>
          <label>
            <span>文件名</span>
            <input v-model.trim="localRecord.title" type="text" placeholder="请输入电影文件名，如 xxx.mp4" />
          </label>
          <label>
            <span>原始文件名</span>
            <input v-model.trim="localRecord.originalName" type="text" placeholder="用于 TMDB 刮削纠错" />
          </label>
          <label>
            <span>所属网盘</span>
            <select v-model="localRecord.sheetId">
              <option v-for="sheet in sheets" :key="sheet.id" :value="sheet.id">{{ sheet.name }}</option>
            </select>
          </label>
          <label>
            <span>评分</span>
            <input v-model.number="localRecord.score" type="number" min="0" max="100" placeholder="0-100" />
          </label>
          <label>
            <span>副标题</span>
            <input v-model.trim="localRecord.subtitle" type="text" placeholder="可选" />
          </label>
          <label>
            <span>分类标签</span>
            <input v-model.trim="localRecord.category" type="text" placeholder="如 科幻 / 动作" />
          </label>
          <label class="field-span-2">
            <span>标签</span>
            <input v-model="tagText" type="text" placeholder="多个标签用逗号分隔" />
          </label>
          <label class="field-span-2">
            <span>描述</span>
            <textarea v-model.trim="localRecord.description" rows="4" placeholder="可选"></textarea>
          </label>
        </template>
      </div>

      <footer>
        <button type="button" class="danger" @click="handleDelete" :disabled="!localRecord.id">删除</button>
        <span></span>
        <button type="button" class="secondary" @click="closeDialog">取消</button>
        <button type="submit">保存</button>
      </footer>
    </form>
  </dialog>
</template>

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

const props = defineProps({
  open: Boolean,
  editingRecord: {
    type: Object,
    default: null,
  },
  sheets: {
    type: Array,
    default: () => [],
  },
  activeSheetId: {
    type: String,
    default: '',
  },
})

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

const dialogRef = ref(null)
const localRecord = ref(createEmptyRecord())

const tagText = computed({
  get: () => (localRecord.value.tags || []).join(', '),
  set: (value) => {
    localRecord.value.tags = value
      .split(',')
      .map((item) => item.trim())
      .filter(Boolean)
  },
})

function createEmptyRecord() {
  return {
    id: null,
    title: '',
    subtitle: '',
    tags: [],
    score: 0,
    originalName: '',
    description: '',
    category: '',
    sheetId: props.activeSheetId || props.sheets[0]?.id || '',
    parentId: null,
  }
}

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

function handleSave() {
  emit('save', {
    ...localRecord.value,
    title: localRecord.value.title?.trim() || '',
    originalName: localRecord.value.originalName?.trim() || '',
    subtitle: localRecord.value.subtitle?.trim() || '',
    description: localRecord.value.description?.trim() || '',
    category: localRecord.value.category?.trim() || '',
  })
  closeDialog()
}

function handleDelete() {
  if (!localRecord.value.id) {
    closeDialog()
    return
  }
  emit('delete', localRecord.value)
  closeDialog()
}

watch(
  () => [props.editingRecord, props.activeSheetId, props.sheets],
  () => {
    localRecord.value = props.editingRecord
      ? {
          ...props.editingRecord,
          tags: [...(props.editingRecord.tags || [])],
          sheetId: props.editingRecord.sheetId || props.activeSheetId || props.sheets[0]?.id || '',
          score: props.editingRecord.score || 0,
        }
      : createEmptyRecord()
  },
  { immediate: true },
)

watch(
  () => props.open,
  (value) => {
    if (!dialogRef.value) return
    if (value && !dialogRef.value.open) {
      dialogRef.value.showModal()
      lockScroll()
    }
    if (!value && dialogRef.value.open) {
      dialogRef.value.close()
      unlockScroll()
    }
  },
)
</script>
