<template>
  <div v-if="visible" class="modal-overlay" @click="handleOverlayClick">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3>{{ title }}</h3>
        <button class="close-btn" @click="handleClose">×</button>
      </div>
      <div class="modal-body">
        <div id="schema-builder-container">
          <div id="schema-builder"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onUnmounted, watch, nextTick } from 'vue'
import { useMessage } from 'naive-ui'
import { t } from '@/shared/i18n'
import $ from 'jquery'

interface Props {
  visible: boolean
  nodeType: string
  nodeName: string
  initialSchema?: any
  onSave?: (schemaData: any) => Promise<void>
  onClose?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  initialSchema: () => ({}),
  onSave: () => Promise.resolve(),
  onClose: () => {}
})

const emit = defineEmits<{
  'update:visible': [value: boolean]
  'save': [schemaData: any]
  'close': []
}>()

const message = useMessage()
const schemaBuilder = ref<any>(null)

const title = computed(() => `${t('Edit')} ${props.nodeType} Schema`)

const ensureDependencies = async () => {
  if (typeof window.$ === 'undefined') {
    window.$ = window.jQuery = $
  }
  
  if (typeof (window as any).jingrow === 'undefined') {
    (window as any).jingrow = {
      ui: {},
      provide: () => {}
    }
  }
}

const initSchemaBuilder = async () => {
  try {
    await ensureDependencies()
    
    await import('/src/core/features/schema_builder/schema_builder.bundle.js' as any)
    
    const container = document.querySelector('#schema-builder')
    if (!container) return
    
    const mockFrm = {
      page: {
        set_title: () => {},
        clear_indicator: () => {},
        set_indicator: () => {}
      },
      is_dirty: () => false,
      dirty: () => {},
      set_value: (field: any, _value: any) => {
        if (field === 'node_schema') {
          // 这里可以触发更新事件
        }
      },
      save: () => Promise.resolve()
    }
    
    // 创建SchemaBuilder实例
    schemaBuilder.value = new (window as any).jingrow.ui.SchemaBuilder({
      wrapper: container,
      frm: mockFrm,
      pagetype: 'Local Ai Node',
      customize: false
    })
    
    // 加载初始Schema数据
    if (props.initialSchema && Object.keys(props.initialSchema).length > 0) {
      schemaBuilder.value.store.loadSchema(props.initialSchema)
    }
    
    // 监听保存事件
    document.addEventListener('schema-save', handleSchemaSave)
    
  } catch (error) {
    console.error('加载SchemaBuilder失败:', error)
    message.error(t('Failed to load Schema Editor') + ': ' + (error as Error).message)
  }
}

const handleSchemaSave = async (event: any) => {
  const schemaData = event.detail.schemaData
  if (schemaData) {
    try {
      await props.onSave(schemaData)
      emit('save', schemaData)
    } catch (e) {
      message.error(t('Save failed, please check permission and server logs'))
    }
  }
}

const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}

const handleOverlayClick = (e: MouseEvent) => {
  if (e.target === e.currentTarget) {
    e.stopPropagation() // 阻止事件冒泡，避免触发列表项的点击事件
    handleClose()
  }
}

const cleanup = () => {
  document.removeEventListener('schema-save', handleSchemaSave)
  if (schemaBuilder.value) {
    schemaBuilder.value = null
  }
}

// 监听 visible 变化
watch(() => props.visible, (newVisible) => {
  if (newVisible) {
    // 延迟初始化，确保 DOM 已渲染
    nextTick(() => {
      initSchemaBuilder()
    })
  } else {
    cleanup()
  }
})

onUnmounted(() => {
  cleanup()
})
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 10000; /* 提高 z-index，确保在列表项之上 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 1200px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 12px 20px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
}

.close-btn:hover {
  background: #f3f4f6;
}

.modal-body {
  flex: 1;
  padding: 12px;
  overflow: auto;
}

#schema-builder-container {
  min-height: 400px;
}
</style>
