<template>
  <n-space>
    <n-button type="info" @click="openSchemaEditor" v-if="!isNew">
      <template #icon>
        <n-icon><Icon icon="tabler:edit" /></n-icon>
      </template>
      {{ t('Edit Schema') }}
    </n-button>
    
    <!-- Schema 编辑器模态框 -->
    <SchemaEditorModal
      v-model:visible="showSchemaEditor"
      :node-type="nodeRecord.node_type || ''"
      :node-name="nodeName"
      :initial-schema="nodeRecord.node_schema || {}"
      :on-save="handleSchemaSave"
      @close="showSchemaEditor = false"
    />
  </n-space>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { NSpace, NButton, NIcon, useMessage } from 'naive-ui'
import { Icon } from '@iconify/vue'
import SchemaEditorModal from '@/core/components/SchemaEditorModal.vue'

const props = defineProps<{ context: {
  entity: any
  id: any
  record: any
  canEdit: any
  loading: any
  save: () => Promise<void> | void
  router: any
  t: (k: string) => string
} }>()

const message = useMessage()
const t = props.context.t
const isNew = computed(() => String(props.context.id?.value || props.context.id) === 'new')
const showSchemaEditor = ref(false)

const nodeName = computed(() => String(props.context.id?.value || props.context.id))
const nodeRecord = computed(() => props.context.record?.value || props.context.record || {})

function openSchemaEditor() {
  if (isNew.value) return
  
  if (!nodeRecord.value.node_type) {
    message.warning(t('Please select node type first'))
    return
  }
  
  showSchemaEditor.value = true
}

async function handleSchemaSave(schemaData: any) {
  try {
    // 更新本地记录
    if (props.context.record?.value) {
      props.context.record.value.node_schema = schemaData
    } else if (props.context.record) {
      props.context.record.node_schema = schemaData
    }
    
    // 调用父组件的保存方法（不传参数，让父组件处理）
    if (props.context.save) {
      await props.context.save()
    } else {
      throw new Error('No save method provided')
    }
    
  } catch (e) {
    throw e // 让组件处理错误显示
  }
}

</script>

<style scoped>
</style>
