<script setup lang="ts">
import type { DatasetRecord } from '../datasetRecords'
import type { EditField } from './types'

defineProps<{
  modelValue: boolean
  record: DatasetRecord | null
  editFields: EditField[]
  rawDraft: string
  savingRecord: boolean
  hasDraftChanges: boolean
  nextVersionNumber: number
}>()

const emit = defineEmits<{
  close: [done?: () => void]
  save: []
  'update:field': [index: number, value: string]
  'update:rawDraft': [value: string]
}>()

function handleBeforeClose(done: () => void) {
  emit('close', done)
}

function handleKeydown(event: KeyboardEvent) {
  if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
    event.preventDefault()
    emit('save')
  }
}
</script>

<template>
  <el-dialog
    :model-value="modelValue"
    class="record-editor-dialog"
    width="min(720px, 92vw)"
    :title="record ? `编辑第 ${record.displayIndex} 条数据` : '编辑数据'"
    :close-on-click-modal="false"
    :close-on-press-escape="!savingRecord"
    :show-close="!savingRecord"
    :before-close="handleBeforeClose"
    destroy-on-close
  >
    <div v-if="record" class="record-editor" @keydown="handleKeydown">
      <div class="editor-hint">
        <i class="fa fa-info-circle" aria-hidden="true" />
        当前修改会先暂存；完成多条修改后，点击文件工具栏中的“保存版本”创建
        V{{ nextVersionNumber }}。
      </div>
      <el-form v-if="record.kind === 'object'" label-position="top">
        <el-form-item v-for="(field, index) in editFields" :key="field.key" :label="field.key">
          <el-input
            :model-value="field.value"
            type="textarea"
            :rows="field.isJson ? 5 : 3"
            :aria-label="`编辑字段 ${field.key}`"
            :placeholder="field.isJson ? '请输入合法 JSON' : `请输入 ${field.key}`"
            @update:model-value="emit('update:field', index, $event)"
          />
          <small v-if="field.isJson" class="field-helper">
            该字段为对象、数组或数值，请保持合法 JSON 格式。
          </small>
        </el-form-item>
      </el-form>
      <div v-else class="raw-record-editor">
        <label for="raw-record-draft">
          {{ record.kind === 'invalid' ? '修复 JSON 内容' : 'JSON 内容' }}
        </label>
        <el-input
          id="raw-record-draft"
          :model-value="rawDraft"
          type="textarea"
          :rows="10"
          aria-label="编辑当前条 JSON 内容"
          placeholder="请输入合法 JSON"
          @update:model-value="emit('update:rawDraft', $event)"
        />
      </div>
    </div>
    <template #footer>
      <div class="record-editor-actions">
        <span>{{ hasDraftChanges ? '有未暂存修改' : '尚未修改' }} · Ctrl/⌘ + S 暂存</span>
        <div>
          <el-button :disabled="savingRecord" @click="emit('close')">取消</el-button>
          <el-button
            type="primary"
            :loading="savingRecord"
            :disabled="!hasDraftChanges"
            @click="emit('save')"
          >
            暂存修改
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.editor-hint {
  margin-bottom: 18px;
  padding: 10px 12px;
  border: 1px solid #dbe2ff;
  border-radius: 8px;
  background: #f5f7ff;
  color: #56627a;
  font-size: 13px;
}

.editor-hint i {
  margin-right: 6px;
  color: var(--primary-color);
}

.field-helper {
  margin-top: 5px;
  color: #8a94a6;
  line-height: 1.5;
}

.raw-record-editor label {
  display: block;
  margin-bottom: 8px;
  color: #344054;
  font-size: 13px;
  font-weight: 600;
}

.record-editor-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
}

.record-editor-actions > span {
  color: #8a94a6;
  font-size: 12px;
}

@media (max-width: 680px) {
  .record-editor-actions {
    align-items: stretch;
    flex-direction: column;
  }

  .record-editor-actions > div {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 8px;
  }
}
</style>
