<template>
  <n-space align="center">
    <!-- 侧边栏位置切换按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      @click="$emit('toggle-sidebar-position')"
      :title="sidebarPosition === 'left' ? '切换到右侧' : '切换到左侧'"
      class="header-action-btn"
    >
      <template #icon>
        <n-icon>
          <Icon :icon="sidebarPosition === 'left' ? 'fluent:panel-right-16-regular' : 'fluent:panel-left-16-regular'" />
        </n-icon>
      </template>
    </n-button>
    
    <!-- 刷新按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      @click="$emit('refresh')"
      :disabled="loading || isNew"
      :title="t('Refresh')"
      class="header-action-btn"
    >
      <template #icon>
        <n-icon>
          <Icon icon="tabler:refresh" />
        </n-icon>
      </template>
    </n-button>
    
    <!-- 删除按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      @click="$emit('delete')"
      :disabled="loading || isNew"
      :title="t('Delete')"
      class="header-action-btn delete-btn"
    >
      <template #icon>
        <n-icon>
          <Icon icon="tabler:trash" />
        </n-icon>
      </template>
    </n-button>
    
    <!-- Edit Schema 按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      @click="openSchemaEditor" 
      v-if="!isNew"
      class="toolbar-btn schema-editor-btn"
    >
      <template #icon>
        <n-icon><Icon icon="tabler:edit" /></n-icon>
      </template>
      {{ t('Edit Schema') }}
    </n-button>
    
    <!-- 返回按钮 -->
    <n-button type="default" size="medium" @click="$emit('go-back')" :disabled="loading">
      <template #icon>
        <n-icon><Icon icon="tabler:arrow-left" /></n-icon>
      </template>
      {{ t('Back') }}
    </n-button>
    
    <!-- 保存按钮 -->
    <n-button 
      type="primary" 
      size="medium" 
      :disabled="loading" 
      @click="$emit('save')" 
      v-if="canEdit" 
      class="save-btn-brand"
    >
      <template #icon>
        <n-icon>
          <Icon icon="tabler:check" />
        </n-icon>
      </template>
      {{ t('Save') }}
    </n-button>
  </n-space>
  
  <!-- 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"
  />
</template>

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

interface Props {
  entity: string
  id: string
  record?: any
  canEdit: boolean
  loading: boolean
  sidebarPosition?: 'left' | 'right'
}

interface Emits {
  (e: 'toggle-sidebar-position'): void
  (e: 'refresh'): void
  (e: 'delete'): void
  (e: 'go-back'): void
  (e: 'save'): void
}

const props = withDefaults(defineProps<Props>(), {
  sidebarPosition: 'left',
  record: () => ({})
})

const emit = defineEmits<Emits>()

const message = useMessage()

// 计算是否为新建记录
const isNew = computed(() => {
  const idValue = props.id
  return idValue === 'new' || idValue.startsWith('new-')
})

// Schema 编辑器相关
const showSchemaEditor = ref(false)
const nodeName = computed(() => String(props.id))
const nodeRecord = computed(() => props.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 {
    // 保存 Schema 数据到后端
    const response = await axios.put(
      `/api/data/${encodeURIComponent(props.entity)}/${encodeURIComponent(nodeName.value)}`, {
        node_schema: schemaData
      })
    
    if (response.data?.success !== false) {
      // 更新本地记录
      if (props.record) {
        props.record.node_schema = schemaData
      }
      message.success(t('Schema saved successfully'))
      showSchemaEditor.value = false
    } else {
      throw new Error(response.data?.message || t('Save failed'))
    }
  } catch (error: any) {
    console.error('保存 Schema 失败:', error)
    message.error(error?.response?.data?.message || error?.message || t('Save failed, please check permission and server logs'))
    throw error // 让组件处理错误显示
  }
}

// 从 localStorage 读取侧边栏位置（如果父组件没有传入）
const sidebarPosition = ref<'left' | 'right'>(props.sidebarPosition || 'left')

// 监听 props 变化
watch(() => props.sidebarPosition, (newPos) => {
  if (newPos) {
    sidebarPosition.value = newPos
  }
}, { immediate: true })

onMounted(() => {
  // 如果没有传入 sidebarPosition，尝试从 localStorage 读取
  if (!props.sidebarPosition) {
    const savedPosition = localStorage.getItem('jingrow-sidebar-position')
    if (savedPosition === 'left' || savedPosition === 'right') {
      sidebarPosition.value = savedPosition
    }
  }
})
</script>

<style scoped>
/* 头部操作按钮统一样式 */
.header-action-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 删除按钮悬浮时使用红色 */
.header-action-btn.delete-btn:hover:not(:disabled) {
  background: #ef4444 !important;
  border-color: #ef4444 !important;
  color: white !important;
}

.header-action-btn.delete-btn:hover:not(:disabled) :deep(.n-button__border),
.header-action-btn.delete-btn:hover:not(:disabled) :deep(.n-button__state-border) {
  border-color: #ef4444 !important;
}

/* 保存按钮 - 使用柔和的品牌色系，与列表页创建按钮一致 */
.save-btn-brand {
  background: #e6f8f0 !important;
  border: 1px solid #1fc76f !important;
  color: #0d684b !important;
}

.save-btn-brand :deep(.n-button__border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand:hover {
  background: #dcfce7 !important;
  border-color: #1fc76f !important;
  border: 1px solid #1fc76f !important;
  color: #166534 !important;
  box-shadow: 0 2px 8px rgba(31, 199, 111, 0.15) !important;
}

.save-btn-brand:hover :deep(.n-button__border),
.save-btn-brand:hover :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand:focus {
  background: #dcfce7 !important;
  border-color: #1fc76f !important;
  border: 1px solid #1fc76f !important;
  color: #166534 !important;
  box-shadow: 0 0 0 2px rgba(31, 199, 111, 0.2) !important;
}

.save-btn-brand:focus :deep(.n-button__border),
.save-btn-brand:focus :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand:active {
  background: #1fc76f !important;
  border-color: #1fc76f !important;
  border: 1px solid #1fc76f !important;
  color: white !important;
  box-shadow: 0 1px 4px rgba(31, 199, 111, 0.2) !important;
}

.save-btn-brand:active :deep(.n-button__border),
.save-btn-brand:active :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand:disabled {
  background: #f1f5f9 !important;
  border: 1px solid #e2e8f0 !important;
  border-color: #e2e8f0 !important;
  color: #94a3b8 !important;
  opacity: 0.6 !important;
  cursor: not-allowed !important;
}

.save-btn-brand:disabled :deep(.n-button__border),
.save-btn-brand:disabled :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

/* 工具栏按钮基础样式 - 与返回按钮一致，使用badge配色方案 */
.toolbar-btn {
  background: #f3f4f6 !important;
  color: #374151 !important;
  border: 1px solid rgba(0, 0, 0, 0.08) !important;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 清除 Naive UI 按钮内部的边框元素，避免双重边框 */
.toolbar-btn :deep(.n-button__border),
.toolbar-btn :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.toolbar-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.toolbar-btn:hover:not(:disabled) :deep(.n-button__border),
.toolbar-btn:hover:not(:disabled) :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

/* 编辑Schema按钮 - 青绿色系（与列表页badge配色一致） */
.schema-editor-btn {
  background: #e6f8f0 !important;
  color: #0d684b !important;
  border-color: rgba(13, 104, 75, 0.2) !important;
}

.schema-editor-btn:hover:not(:disabled) {
  background: #d1f2e5 !important;
  color: #0a5543 !important;
  border-color: rgba(13, 104, 75, 0.3) !important;
  box-shadow: 0 2px 8px rgba(13, 104, 75, 0.15);
}

.toolbar-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.toolbar-btn:disabled :deep(.n-button__border),
.toolbar-btn:disabled :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}
</style>

