<template>
  <div class="flow-builder-page">
    <div v-if="!hasValidParams" class="empty-state">
      <div class="empty-content">
        <h3>{{ t('Flow Builder') }}</h3>
        <p>{{ t('Please enter from Agents page to open Flow Builder') }}</p>
        <n-button type="primary" @click="goToAgents">{{ t('View Agents') }}</n-button>
      </div>
    </div>
    <FlowBuilderContainer 
      v-else
      :initial-value="flowBuilderStore.getFlowData()"
      :agent-id="agentId"
      @save="handleSave"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useMessage, NButton } from 'naive-ui'
import FlowBuilderContainer from '@/core/features/flows/FlowBuilderContainer.vue'
import { useAgentStore } from '@/shared/stores/agent'
import { useFlowBuilderStore } from '@/shared/stores/flowBuilder'
import { t } from '@/shared/i18n'

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

// 计算属性 - 优先使用store，fallback到URL参数
const agentId = computed(() => {
  return flowBuilderStore.getAgentId() || (route.query.agentId as string)
})

// 检查是否有有效参数
const hasValidParams = computed(() => {
  return agentId.value || flowBuilderStore.hasFlowData()
})

// 页面挂载时恢复状态
onMounted(async () => {
  const urlAgentId = route.query.agentId as string
  if (urlAgentId && !flowBuilderStore.getAgentId()) {
    try {
      // 从URL恢复agentId到store
      flowBuilderStore.setAgentId(urlAgentId)
      
      // 获取智能体数据并加载流程
      await agentStore.fetchAgent(urlAgentId)
      const agent = agentStore.currentAgent
      if (agent?.agent_flow) {
        let flowData = agent.agent_flow
        if (typeof flowData === 'string') {
          flowData = JSON.parse(flowData)
        }
        flowBuilderStore.setFlowData(flowData)
      }
    } catch (error) {
      console.error('恢复智能体数据失败:', error)
    }
  }
})

// 方法
const handleSave = async (flowData: any) => {
  try {
    if (agentId.value) {
      // 保存到智能体
      await agentStore.updateAgent(agentId.value, { agent_flow: flowData })
      message.success(t('Agent flow saved successfully'))
      // 保存成功后清理store状态
      flowBuilderStore.deactivateFlowBuilder()
    } else {
      // 作为独立流程保存
      console.log('保存流程数据:', flowData)
      message.success(t('Flow saved successfully'))
    }
  } catch (error: any) {
    message.error(t('Save failed') + ': ' + (error?.message || ''))
  }
}

const goToAgents = () => {
  router.push('/agents')
}
</script>

<style scoped>
.flow-builder-page {
  width: 100%;
  margin: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-description {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.flow-builder-container {
  height: 600px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-state {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8fafc;
}

.empty-content {
  text-align: center;
  padding: 40px;
}

.empty-content h3 {
  margin: 0 0 16px 0;
  font-size: 24px;
  color: #1f2937;
}

.empty-content p {
  margin: 0 0 24px 0;
  font-size: 16px;
  color: #6b7280;
}
</style>
