<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" class="save-btn-brand">
            <template #icon>
              <n-icon>
                <Icon icon="tabler:check" />
              </n-icon>
            </template>
            {{ 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 { slugToPageType } from '@/shared/utils/slug'
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())

// 从 URL 获取 pagetype 参数
const pagetype = computed(() => {
  const query = router.currentRoute.value.query
  const slug = query.pagetype as string
  return slug ? slugToPageType(slug) : ''
})

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

// 监听 agentId 变化，获取智能体名称
watch(
  agentId,
  async (id) => {
    if (id) {
      try {
        await agentStore.fetchAgent(id, pagetype.value)
        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 }, pagetype.value)
      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; }

/* 保存按钮 - 使用柔和的品牌色系，与详情页保存按钮一致 */
.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;
}
</style>
