<template>
  <div class="page">
    <!-- 二级操作栏 -->
    <div class="secondary-bar">
      <div class="left-actions">
        <button class="btn btn-outline" @click="openSchemaEditor">
          <i class="fa fa-edit"></i> {{ t('Edit Schema') }}
        </button>
        <button class="btn btn-primary" :disabled="saving" @click="save">
          <i :class="saving ? 'fa fa-spinner fa-spin' : 'fa fa-save'"></i> {{ t('Save') }}
        </button>
      </div>
    </div>

    <div class="main-layout">
      <!-- 主内容区域 -->
      <div class="main-content">
        <div v-if="loading" class="loading">
          <i class="fa fa-spinner fa-spin"></i> {{ t('Loading...') }}
        </div>
        <div v-else class="content-grid">
          <!-- 节点元数据卡片 -->
          <div class="properties-card">
            <h4>{{ t('Node Metadata') }}</h4>
            <div class="properties-grid">
              <div class="property-group">
                <div class="property-item">
                  <label>{{ t('Node Type') }}</label>
                  <input type="text" v-model="nodeRecord.node_type" />
                </div>
                <div class="property-item">
                  <label>{{ t('Node Label') }}</label>
                  <input type="text" v-model="nodeRecord.node_label" />
                </div>
                <div class="property-item">
                  <label>{{ t('Node Icon') }}</label>
                  <input type="text" v-model="nodeRecord.node_icon" />
                </div>
                <div class="property-item">
                  <label>{{ t('Node Color') }}</label>
                  <div class="color-picker">
                    <input type="color" v-model="nodeRecord.node_color" />
                    <input type="text" v-model="nodeRecord.node_color" />
                  </div>
                </div>
              </div>
              <div class="property-group">
                <div class="property-item">
                  <label>{{ t('Status') }}</label>
                  <n-select v-model:value="nodeRecord.status" :options="statusOptions" clearable/>
                </div>
                <div class="property-item">
                  <label>{{ t('Node Group') }}</label>
                  <n-select v-model:value="nodeRecord.node_group" :options="groupOptions" filterable clearable/>
                </div>
                <div class="property-item">
                  <label>{{ t('Node Component') }}</label>
                  <n-select v-model:value="nodeRecord.node_component" :options="componentOptions" filterable clearable/>
                </div>
                <div class="property-item full-width">
                  <label>{{ t('Node Description') }}</label>
                  <textarea v-model="nodeRecord.node_description"></textarea>
                </div>
              </div>
            </div>
        </div>

          <!-- Schema编辑器卡片 -->
          <div class="editor-card">
            <div class="editor-header">
              <h4>{{ t('Node Schema') }}</h4>
            </div>
            <div class="editor-container">
          <textarea v-model="schemaText" spellcheck="false" />
            </div>
          </div>

          
        </div>
      </div>
    </div>
    
    <!-- Schema 编辑器模态框 -->
    <SchemaEditorModal
      v-model:visible="showSchemaEditor"
      :node-type="nodeRecord.node_type || ''"
      :node-name="nodeName"
      :initial-schema="schema"
      :on-save="handleSchemaSave"
      @close="showSchemaEditor = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import $ from 'jquery'
import { useMessage, NSelect } from 'naive-ui'
import { t } from '@/shared/i18n'
import { checkNodeTypeExists, createNode, getNodeGroups, getNodeComponents, getNodeStatusOptions, getNodeRecord, updateNode, exportNodeDefinition } from '@/shared/api/nodes'
import SchemaEditorModal from '@/core/components/SchemaEditorModal.vue'

declare global {
  interface Window { $: typeof $; jQuery: typeof $; jingrow: any }
}
window.$ = window.jQuery = $

const route = useRoute()
const message = useMessage()

const nodeName = computed(() => String(route.params.name || ''))
const isNew = computed(() => nodeName.value === 'new' || nodeName.value === '')
const loading = ref(true)
const saving = ref(false)
const showSchemaEditor = ref(false)
const nodeRecord = ref<any>({})
const schema = ref<any>({})
const schemaText = ref('')
const groupOptions = ref<{ label: string; value: string }[]>([])
const componentOptions = ref<{ label: string; value: string }[]>([])
const statusOptions = ref<{ label: string; value: string }[]>([])

async function load() {
  loading.value = true
  try {
    if (isNew.value) {
      // 新建模式：初始化空对象，不请求后端
      nodeRecord.value = { node_type: '', node_label: '', node_icon: '', node_color: '#6b7280', node_group: '', node_component: '', node_description: '', status: 'Draft' }
      schema.value = {}
      schemaText.value = JSON.stringify(schema.value, null, 2)
      await loadSelectOptions()
      return
    }
    // 编辑模式：获取节点记录（包含所有字段）
    const recordData = await getNodeRecord(nodeName.value)
    nodeRecord.value = recordData || {}
    
    // 从 node_schema 字段获取 schema
    schema.value = nodeRecord.value.node_schema || {}
    
    schemaText.value = JSON.stringify(schema.value, null, 2)
    await loadSelectOptions()
  } catch (e) {
    message.error(t('Load failed') + ': ' + (e instanceof Error ? e.message : String(e)))
  } finally {
    loading.value = false
  }
}

async function loadSelectOptions() {
  try {
    const [groups, components, statuses] = await Promise.all([
      getNodeGroups(),
      getNodeComponents(),
      getNodeStatusOptions()
    ])
    groupOptions.value = groups.map((g: string) => ({ label: t(g), value: g }))
    componentOptions.value = components.map((c: string) => ({ label: t(c), value: c }))
    statusOptions.value = statuses.map((s: string) => ({ label: t(s), value: s }))
  } catch (_) {
    groupOptions.value = []
    componentOptions.value = []
    statusOptions.value = []
  }
}

async function save() {
  let schemaBody: any
  try {
    schemaBody = JSON.parse(schemaText.value)
  } catch (e) {
    message.error(t('Invalid JSON, please fix before saving'))
    return
  }
  saving.value = true
  try {
    if (isNew.value) {
      if (!nodeRecord.value.node_type) {
        message.warning(t('Please enter Node Type'))
        return
      }
      const exists = await checkNodeTypeExists(nodeRecord.value.node_type)
      if (exists) {
        message.error(t('Node Type already exists'))
        return
      }

      const result = await createNode({
        node_type: nodeRecord.value.node_type,
        node_label: nodeRecord.value.node_label,
        node_icon: nodeRecord.value.node_icon,
        node_color: nodeRecord.value.node_color,
        node_group: nodeRecord.value.node_group,
        node_component: nodeRecord.value.node_component,
        node_description: nodeRecord.value.node_description,
        status: nodeRecord.value.status || 'Draft',
        node_schema: schemaBody
      })
      const created = result?.data ?? result
      const newName = created?.name
        ?? created?.data?.name
        ?? created?.message?.name
        ?? created?.document?.name
      if (!result?.success) {
        const msg = result?.message || 'create failed'
        if (/Duplicate|exists|unique/i.test(String(msg))) {
          message.error(t('Node Type already exists'))
          return
        }
      }
      if (result?.success && newName) {
        message.success(t('Created successfully'))
        // 写入服务器 JSON
        try {
          await exportNodeDefinition({
            metadata: {
              type: nodeRecord.value.node_type,
              label: nodeRecord.value.node_label,
              icon: nodeRecord.value.node_icon,
              color: nodeRecord.value.node_color,
              description: nodeRecord.value.node_description,
              group: nodeRecord.value.node_group,
              component_type: nodeRecord.value.node_component || 'GenericNode'
            },
            schema: schemaBody
          })
        } catch (_) {}
        // 延迟跳转到新节点的详情页
        setTimeout(() => {
          window.location.href = `/nodes/${encodeURIComponent(newName)}`
        }, 1500)
        return
      }
      throw new Error('create failed')
    }
    // 编辑模式：更新
    const nodeData = { ...nodeRecord.value, node_schema: schemaBody }
    await updateNode(nodeName.value, nodeData)
    // 写入服务器 JSON
    try {
      await exportNodeDefinition({
        metadata: {
          type: nodeRecord.value.node_type,
          label: nodeRecord.value.node_label,
          icon: nodeRecord.value.node_icon,
          color: nodeRecord.value.node_color,
          description: nodeRecord.value.node_description,
          group: nodeRecord.value.node_group,
          component_type: nodeRecord.value.node_component || 'GenericNode'
        },
        schema: schemaBody
      })
    } catch (_) {}
    message.success(t('Saved successfully'))
    await load()
  } catch (e) {
    message.error(t('Save failed, please check permission and server logs'))
  } finally {
    saving.value = false
  }
}

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

async function handleSchemaSave(schemaData: any) {
  try {
    // 准备完整的节点数据
    const nodeData = {
      ...nodeRecord.value,
      node_schema: schemaData
    }
    
    // 调用更新API
    await updateNode(nodeName.value, nodeData)
    
    // 更新本地数据
    schema.value = schemaData
    schemaText.value = JSON.stringify(schemaData, null, 2)
    
    // 重新加载数据以确保同步
    await load()
    
  } catch (e) {
    throw e // 让组件处理错误显示
  }
}


watch(() => route.params.name, load)
onMounted(load)
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f8fafc;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 顶部导航栏 */
.top-bar {
  background: #fff;
  border-bottom: 1px solid #e5e7eb;
  padding: 12px 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: sticky;
  top: 0;
  z-index: 10;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #64748b;
  font-size: 14px;
}

.breadcrumb i {
  font-size: 12px;
}

.top-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.search-box {
  position: relative;
  display: flex;
  align-items: center;
}

.search-box i {
  position: absolute;
  left: 12px;
  color: #94a3b8;
  font-size: 14px;
}

.search-box input {
  padding: 8px 12px 8px 36px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: #f8fafc;
  font-size: 14px;
  width: 200px;
}

.search-box input:focus {
  outline: none;
  border-color: #3b82f6;
  background: #fff;
}

.icon-btn {
  background: none;
  border: none;
  padding: 8px;
  border-radius: 6px;
  cursor: pointer;
  color: #64748b;
  transition: all 0.2s;
}

.icon-btn:hover {
  background: #f1f5f9;
  color: #334155;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #3b82f6;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 14px;
}

.user-avatar.small {
  width: 24px;
  height: 24px;
  font-size: 12px;
}

/* 二级操作栏 */
.secondary-bar {
  background: #fff;
  border-bottom: 1px solid #e5e7eb;
  padding: 8px 16px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.left-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 主布局 */
.main-layout { display: block; min-height: calc(100vh - 60px); }

/* Schema编辑器对话框样式 */
.schema-editor-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 20;
}

.dialog-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.dialog-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 1200px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

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

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

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #6b7280;
  padding: 4px;
}

.close-btn:hover {
  color: #374151;
}

.dialog-body {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.dialog-footer {
  padding: 20px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

#schema-builder-container {
  min-height: 400px;
}

/* 主内容区域 */
.main-content { flex: 1; padding: 24px; overflow-y: auto; max-width: none; }

.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 48px;
  color: #64748b;
  font-size: 16px;
}

.content-grid { display: flex; flex-direction: column; gap: 24px; width: 100%; max-width: none; }

/* 卡片样式 */
.properties-card,
.editor-card {
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.properties-card h4,
.editor-card h4 {
  margin: 0 0 20px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

/* 属性网格 */
.properties-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px; }

.property-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.property-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.property-item.full-width {
  grid-column: 1 / -1;
}

.property-item label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.property-item input,
.property-item textarea {
  padding: 10px 12px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.2s;
}

.property-item input:focus,
.property-item textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.property-item input[readonly] {
  background: #f9fafb;
  color: #6b7280;
}

.color-picker {
  display: flex;
  gap: 8px;
  align-items: center;
}

.color-picker input[type="color"] {
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
}

.color-picker input[type="text"] {
  flex: 1;
}

/* 编辑器 */
.editor-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.editor-container textarea {
  width: 100%;
  height: 560px;
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.6;
  padding: 16px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  background: #f9fafb;
  color: #111827;
  resize: vertical;
  transition: all 0.2s;
}

.editor-container textarea:focus {
  outline: none;
  border-color: #3b82f6;
  background: #fff;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.editor-container textarea::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 4px;
  transition: all 0.2s ease;
  cursor: pointer;
}
/* 评论区域 */
.comment-input {
  display: flex;
  gap: 12px;
  align-items: center;
}

.comment-input input {
  flex: 1;
  padding: 10px 12px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 14px;
}

.comment-input input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* 按钮样式 */
.btn {
  padding: 6px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background: #fff;
  cursor: pointer;
  font-size: 13px;
  font-weight: 500;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.btn:hover {
  background: #f9fafb;
  border-color: #9ca3af;
}

.btn-outline {
  background: #fff;
  color: #374151;
}

.btn-primary {
  background: #1e293b;
  color: #fff;
  border-color: #1e293b;
}

.btn-primary:hover {
  background: #334155;
  border-color: #334155;
}

.btn-sm {
  padding: 6px 12px;
  font-size: 13px;
}

.btn[disabled] {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn[disabled]:hover {
  background: #fff;
  border-color: #d1d5db;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .properties-grid { grid-template-columns: 1fr; }
}

@media (max-width: 768px) {
  .main-layout { flex-direction: column; }
  
  .top-bar,
  .secondary-bar {
    padding: 12px 16px;
  }
  
  .main-content {
    padding: 16px;
  }
}
</style>


