<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="name"
      @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 { slugToPageType } from '@/shared/utils/slug'
import { t } from '@/shared/i18n'

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

// 计算属性 - 从 URL 获取参数
const name = computed(() => {
  return (route.query.id as string) || (route.query.name as string) || flowBuilderStore.getAgentId()
})

const pagetype = computed(() => {
  const slug = route.query.pagetype as string
  return slug ? slugToPageType(slug) : ''
})

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

// 页面挂载时恢复状态
onMounted(async () => {
  const urlName = (route.query.id as string) || (route.query.name as string)
  const urlPageType = pagetype.value
  
  if (urlName && !flowBuilderStore.getAgentId()) {
    try {
      // 获取智能体数据
      await agentStore.fetchAgent(urlName, urlPageType)
      const agent = agentStore.currentAgent
      if (agent?.agent_flow) {
        let flowData = agent.agent_flow
        if (typeof flowData === 'string') {
          flowData = JSON.parse(flowData)
        }
        flowBuilderStore.activateFlowBuilder(flowData, urlName)
      }
    } catch (error) {
      console.error('恢复智能体数据失败:', error)
    }
  }
})

// 方法
const handleSave = async (flowData: any) => {
  try {
    if (name.value) {
      // 保存到智能体
      await agentStore.updateAgent(name.value, { agent_flow: flowData }, pagetype.value)
      message.success(t('Agent flow saved successfully'))
      // 保存成功后清理 store 状态
      flowBuilderStore.deactivateFlowBuilder()
    } else {
      // 作为独立流程保存
      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>
