<template>
  <div class="flow-builder">
    <div class="flow-builder-header">
      <div class="header-left">
        <h2 class="title">{{ pageTitle }}</h2>
      </div>
      <div class="header-right">
        <n-space>
          <n-button size="small" @click="handleBack">
            <template #icon>
              <n-icon><Icon icon="tabler:arrow-left" /></n-icon>
            </template>
            {{ t('Back') }}
          </n-button>
          <n-button size="small" type="primary" @click="handleSave">{{ t('Save') }}</n-button>
        </n-space>
      </div>
    </div>
    
    <div class="flow-builder-content">
      <AIAgentFlowBuilder 
        ref="flowBuilderRef"
        :initial-value="computedInitialValue"
        :agent-id="agentId"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { NSpace, NButton, NIcon, useMessage } from 'naive-ui'
import { Icon } from '@iconify/vue'
// @ts-ignore
import AIAgentFlowBuilder from './AIAgentFlowBuilder.vue'
import { useFlowBuilderStore } from '@/shared/stores/flowBuilder'
import { useAgentStore } from '@/shared/stores/agent'
import { t } from '@/shared/i18n'

// Props
const props = defineProps<{ initialValue?: any; agentId?: string }>()

// Emits
const emit = defineEmits(['save'])

const router = useRouter()
const message = useMessage()
const agentStore = useAgentStore()
const flowBuilderStore = useFlowBuilderStore()

// 响应式数据
const agentName = ref('')

// 计算属性 - 优先使用props，fallback到store
const computedInitialValue = computed(() => {
  if (props.initialValue && Object.keys(props.initialValue).length > 0) return props.initialValue
  const storeData = flowBuilderStore.getFlowData()
  if (storeData && Object.keys(storeData).length > 0) return storeData
  return {}
})

// Refs
const flowBuilderRef = ref()

// Computed - 优先使用props，fallback到store
const agentId = computed(() => props.agentId || flowBuilderStore.getAgentId())

// 页面标题
const pageTitle = computed(() => (agentName.value ? `${agentName.value}` : t('Flow Builder')))

// 监听agentId变化，获取智能体名称
watch(
  agentId,
  async (id) => {
    if (id) {
      try {
        await agentStore.fetchAgent(id)
        agentName.value = agentStore.currentAgent?.agent_name || agentStore.currentAgent?.name || ''
      } catch (error) {
        console.error('获取智能体信息失败:', error)
        agentName.value = ''
      }
    } else {
      agentName.value = ''
    }
  },
  { immediate: true }
)

// Methods
const handleSave = async () => {
  try {
    if (!flowBuilderRef.value) {
      message.error(t('Flow Builder is not initialized'))
      return
    }

    const flowData = flowBuilderRef.value.getFlowData()
    
    if (agentId.value) {
      await agentStore.updateAgent(agentId.value, { agent_flow: flowData })
      message.success(t('Flow saved successfully'))
    } else {
      emit('save', flowData)
      message.success(t('Flow saved successfully'))
    }
    
  } catch (error: any) {
    message.error(t('Save failed') + ': ' + (error.message || t('An error occurred during save')))
  }
}

const handleBack = () => {
  flowBuilderStore.deactivateFlowBuilder()
  router.back()
}
</script>

<style scoped>
.flow-builder { height: 88vh; display: flex; flex-direction: column; }
.flow-builder-header { display: flex; justify-content: space-between; align-items: center; padding: 6px 16px; border-bottom: 1px solid #e5e7eb; background: white; min-height: 40px; }
.header-left .title { margin: 0; font-size: 18px; font-weight: 600; color: #1f2937; }
.flow-builder-content { flex: 1; overflow: hidden; }
</style>
