<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>
    
    <!-- 执行按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      :disabled="executing || loading" 
      @click="handleExecute" 
      v-if="!isNew"
      class="toolbar-btn execute-btn"
    >
      <template #icon>
        <n-icon><Icon icon="tabler:play" /></n-icon>
      </template>
      {{ executing ? t('Executing...') : t('Execute') }}
    </n-button>
    
    <!-- 流程编排按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      @click="handleFlowBuilder"
      :disabled="loading"
      class="toolbar-btn flow-builder-btn"
    >
      <template #icon>
        <n-icon><Icon icon="lucide:workflow" /></n-icon>
      </template>
      {{ t('Flow Builder') }}
    </n-button>
    
    <!-- 发布到市场按钮 -->
    <n-button 
      type="default" 
      size="medium" 
      @click="handlePublish"
      :disabled="loading || isNew || publishing"
      class="toolbar-btn publish-btn"
      v-if="!isNew"
    >
      <template #icon>
        <n-icon><Icon icon="tabler:cloud-upload" /></n-icon>
      </template>
      {{ publishing ? t('Publishing...') : t('Publish to Marketplace') }}
    </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>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { NButton, NSpace, NIcon, useMessage, useDialog } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { useRouter } from 'vue-router'
import { t } from '@/shared/i18n'
import { api } from '@/shared/api/common'
import { pageTypeToSlug } from '@/shared/utils/slug'
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: () => ({})
})

defineEmits<Emits>()

const message = useMessage()
const dialog = useDialog()
const router = useRouter()
const executing = ref(false)
const publishing = ref(false)

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

// 从 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
    }
  }
})

// 执行按钮处理函数
async function handleExecute() {
  if (isNew.value) return
  
  const agentName = props.record?.name
  if (!agentName) {
    message.error(t('Agent name is required'))
    return
  }
  
  try {
    executing.value = true
    
    const res = await api.call('jingrow.ai.pagetype.ai_agent.ai_agent.execute_agent_by_name', {
      agent_name: agentName
    })
    
    const result = res?.message || res
    
    if (result?.success) {
      message.success(result.message || t('Agent execution started successfully'))
    } else {
      message.error(result?.error || t('Execution failed'))
    }
  } catch (error: any) {
    message.error(error?.message || t('Execution failed'))
  } finally {
    executing.value = false
  }
}

// 流程编排按钮处理函数
async function handleFlowBuilder() {
  try {
    const raw = props.record?.agent_flow ?? {}
    let flowData: any = raw
    if (typeof raw === 'string') {
      try { flowData = JSON.parse(raw) } catch { flowData = {} }
    }
    const name = props.record?.name || ''
    const pagetype = pageTypeToSlug(props.entity)
    
    const { useFlowBuilderStore } = await import('@/shared/stores/flowBuilder')
    const flowBuilderStore = useFlowBuilderStore()
    
    flowBuilderStore.activateFlowBuilder(flowData, name)
    
    router.push({ name: 'FlowBuilder', query: { pagetype, id: name } })
  } catch (_) {}
}

// 发布到市场按钮处理函数
function handlePublish() {
  if (isNew.value || !props.record?.agent_name) {
    message.warning(t('Please save the agent first'))
    return
  }
  
  const agentName = props.record.agent_name
  const agentFlow = props.record.agent_flow
  
  if (!agentFlow) {
    message.warning(t('Agent flow data is required for publishing'))
    return
  }
  
  dialog.info({
    title: t('Publish to Agent Marketplace'),
    content: t('Are you sure you want to publish agent "{0}" to the marketplace?').replace('{0}', agentName),
    positiveText: t('Confirm'),
    negativeText: t('Cancel'),
    onPositiveClick: () => {
      performPublish()
    }
  })
}

async function performPublish() {
  try {
    publishing.value = true
    
    const agentName = props.record?.agent_name || ''
    const agentFlow = props.record?.agent_flow
    
    if (!agentFlow) {
      throw new Error(t('Agent flow data is required'))
    }
    
    // agent_flow 是 JSON 字段类型，从数据库获取时可能是字符串或对象
    // 统一处理：如果是字符串则解析为对象，如果是对象则直接使用
    let flowData = agentFlow
    if (typeof agentFlow === 'string') {
      try {
        flowData = JSON.parse(agentFlow)
      } catch (e) {
        throw new Error(t('Invalid agent flow data format'))
      }
    } else if (typeof agentFlow !== 'object' || agentFlow === null) {
      throw new Error(t('Agent flow data must be a valid JSON object'))
    }
    
    // 准备发布数据（flowData 现在是对象，后端会处理 JSON 序列化）
    const publishData = {
      agent_name: agentName,
      title: props.record?.title || agentName,
      subtitle: props.record?.subtitle || '',
      description: props.record?.description || '',
      agent_flow: flowData  // 对象格式，axios 会自动序列化为 JSON
    }
    
    const response = await axios.post('/jingrow/agent/publish', publishData, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data.success) {
      message.success(response.data.message || t('Agent published successfully'))
    } else {
      throw new Error(response.data.message || t('Publish failed'))
    }
  } catch (error: any) {
    console.error('发布智能体失败:', error)
    const errorMsg = error?.response?.data?.detail || error?.response?.data?.message || error?.message || t('Publish failed, please check permission and server logs')
    message.error(errorMsg)
  } finally {
    publishing.value = false
  }
}
</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;
}

/* 执行按钮 - 绿色系（与列表页badge配色一致） */
.execute-btn {
  background: #dcfce7 !important;
  color: #166534 !important;
  border-color: rgba(34, 197, 94, 0.2) !important;
}

.execute-btn:hover:not(:disabled) {
  background: #bbf7d0 !important;
  color: #15803d !important;
  border-color: rgba(34, 197, 94, 0.3) !important;
  box-shadow: 0 2px 8px rgba(34, 197, 94, 0.15);
}

/* 流程编排按钮 - 蓝色系（与列表页badge配色一致） */
.flow-builder-btn {
  background: #e0f2fe !important;
  color: #0369a1 !important;
  border-color: rgba(14, 165, 233, 0.2) !important;
}

.flow-builder-btn:hover:not(:disabled) {
  background: #bae6fd !important;
  color: #0284c7 !important;
  border-color: rgba(14, 165, 233, 0.3) !important;
  box-shadow: 0 2px 8px rgba(14, 165, 233, 0.15);
}

/* 发布按钮 - 紫色系 */
.publish-btn {
  background: #f3e8ff !important;
  color: #7c3aed !important;
  border-color: rgba(139, 92, 246, 0.2) !important;
}

.publish-btn:hover:not(:disabled) {
  background: #e9d5ff !important;
  color: #6d28d9 !important;
  border-color: rgba(139, 92, 246, 0.3) !important;
  box-shadow: 0 2px 8px rgba(139, 92, 246, 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>

