<template>
  <a-drawer
    :open="open"
    title="字段管理"
    placement="right"
    :width="480"
    @close="handleClose"
  >
    <!-- U2: positioning hint — single-field edits now happen inline via the
         column header menu; this drawer remains the batch-management entry. -->
    <a-alert
      class="field-manage-panel__hint"
      type="info"
      show-icon
      message="批量管理入口"
      description="单字段编辑请使用列头菜单中的「编辑字段」。此处用于批量管理字段。"
    />

    <!-- Field list -->
    <div class="field-manage-panel__list">
      <div
        v-for="f in fields"
        :key="f.id"
        class="field-manage-panel__item"
      >
        <div class="field-manage-panel__item-info">
          <span class="field-manage-panel__item-name">{{ f.name }}</span>
          <div class="field-manage-panel__item-meta">
            <a-tag :color="typeColor(f.field_type)">{{ typeLabel(f.field_type) }}</a-tag>
            <a-tag :color="f.owner === 'agent' ? 'default' : 'success'">
              {{ f.owner === 'agent' ? 'Agent' : '用户' }}
            </a-tag>
          </div>
        </div>
        <div class="field-manage-panel__item-actions">
          <a-button type="text" size="small" @click="handleEdit(f)">编辑</a-button>
          <a-button type="text" size="small" danger @click="handleDelete(f)">删除</a-button>
        </div>
      </div>

      <a-empty v-if="fields.length === 0" description="暂无字段" />
    </div>

    <!-- Add field button -->
    <div class="field-manage-panel__add">
      <a-button type="dashed" block :icon="h(PlusOutlined)" @click="handleAdd">
        添加字段
      </a-button>
    </div>

    <!-- Edit/Add modal -->
    <a-modal
      :open="editModalOpen"
      :title="editingField ? '编辑字段' : '新增字段'"
      :confirm-loading="saving"
      @ok="handleSave"
      @cancel="editModalOpen = false"
    >
      <FieldConfigForm
        v-if="editModalOpen"
        ref="formRef"
        :field="editingField"
      />
    </a-modal>

    <!-- Delete dependency confirmation -->
    <a-modal
      :open="deleteConfirmOpen"
      title="确认删除"
      @ok="handleForceDelete"
      @cancel="deleteConfirmOpen = false"
    >
      <p>该字段被以下内容引用，强制删除将级联清理：</p>
      <pre class="field-manage-panel__deps">{{ JSON.stringify(deleteDependencies, null, 2) }}</pre>
    </a-modal>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, h } from 'vue'
import { Modal as AModal, Drawer as ADrawer, Button as AButton, Tag as ATag, Empty as AEmpty, Alert as AAlert } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import type { IBitableField, FieldType } from '@/api/bitable'
import { useBitableStore } from '@/stores/bitable'
import FieldConfigForm from './FieldConfigForm.vue'

defineProps<{
  open: boolean
  fields: IBitableField[]
}>()

const emit = defineEmits<{
  (e: 'close'): void
}>()

const store = useBitableStore()

const editModalOpen = ref(false)
const editingField = ref<IBitableField | null>(null)
const saving = ref(false)
const formRef = ref<InstanceType<typeof FieldConfigForm> | null>(null)

// Delete confirmation state
const deleteConfirmOpen = ref(false)
const deleteTargetId = ref<string | null>(null)
const deleteDependencies = ref<Record<string, unknown>>({})

function handleClose(): void {
  emit('close')
}

function handleAdd(): void {
  editingField.value = null
  editModalOpen.value = true
}

function handleEdit(field: IBitableField): void {
  editingField.value = field
  editModalOpen.value = true
}

async function handleSave(): Promise<void> {
  const form = formRef.value
  if (!form) return

  if (!form.isFormulaValid()) {
    AModal.warning({
      title: '公式语法错误',
      content: '请修正公式表达式后再保存',
    })
    return
  }

  const data = form.getData()
  if (!data.name) {
    AModal.warning({ title: '请输入字段名称' })
    return
  }

  saving.value = true
  try {
    if (editingField.value) {
      // Update existing field
      await store.updateField(editingField.value.id, {
        name: data.name,
        config: data.config,
      })
    } else {
      // Create new field
      await store.addField(data.name, data.fieldType, data.config)
    }
    editModalOpen.value = false
  } finally {
    saving.value = false
  }
}

async function handleDelete(field: IBitableField): Promise<void> {
  const result = await store.deleteField(field.id)
  if (!result.success && result.dependencies) {
    // Has dependencies — show confirmation
    deleteTargetId.value = field.id
    deleteDependencies.value = result.dependencies
    deleteConfirmOpen.value = true
  }
}

async function handleForceDelete(): Promise<void> {
  if (!deleteTargetId.value) return
  await store.deleteField(deleteTargetId.value, true)
  deleteConfirmOpen.value = false
  deleteTargetId.value = null
  deleteDependencies.value = {}
}

// ── Helpers ──────────────────────────────────────────────

function typeLabel(t: FieldType): string {
  const labels: Record<FieldType, string> = {
    text: '文本',
    number: '数字',
    date: '日期',
    select: '单选',
    multiselect: '多选',
    attachment: '附件',
    image: '图片',
    formula: '公式',
    lookup: '引用',
  }
  return labels[t] ?? t
}

function typeColor(t: FieldType): string {
  const colors: Partial<Record<FieldType, string>> = {
    text: 'default',
    number: 'blue',
    date: 'purple',
    select: 'cyan',
    multiselect: 'cyan',
    formula: 'orange',
    lookup: 'magenta',
    attachment: 'geekblue',
    image: 'geekblue',
  }
  return colors[t] ?? 'default'
}
</script>

<style scoped>
.field-manage-panel__hint {
  margin-bottom: var(--bitable-spacing-md);
  border-radius: var(--bitable-radius-md);
}

.field-manage-panel__list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}

.field-manage-panel__item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border: 1px solid var(--border-color, #f0f0f0);
  border-radius: 6px;
}

.field-manage-panel__item-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.field-manage-panel__item-name {
  font-weight: 500;
  font-size: 14px;
}

.field-manage-panel__item-meta {
  display: flex;
  gap: 4px;
}

.field-manage-panel__item-actions {
  display: flex;
  gap: 4px;
}

.field-manage-panel__add {
  margin-top: 16px;
}

.field-manage-panel__deps {
  background: var(--bg-secondary, #fafafa);
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  max-height: 300px;
  overflow: auto;
}
</style>
