<template>
  <div class="agent-detail-page">
    <div class="page-header">
      <n-space justify="space-between" align="center">
        <div>
          <h1 class="page-title">{{ isNew ? t('Create Agent') : (agent?.agent_name || t('Agent Detail')) }}</h1>
          <p class="page-description">{{ isNew ? t('Create a new AI agent') : t('View and manage agent settings') }}</p>
        </div>
        <n-space>
          <n-button v-if="!isNew && canExecute" type="success" :disabled="executing" @click="handleExecute">
            <template #icon>
              <n-icon><Icon icon="tabler:play" /></n-icon>
            </template>
            {{ executing ? t('Executing...') : t('Execute') }}
          </n-button>
          <n-button type="info" @click="handleFlowBuilder">
            <template #icon>
              <n-icon><Icon icon="tabler:workflow" /></n-icon>
            </template>
            {{ t('Flow Builder') }}
          </n-button>
          <n-button type="primary" :disabled="saving" @click="handleSave">
            <template #icon>
              <n-icon><Icon icon="tabler:edit" /></n-icon>
            </template>
            {{ t('Save') }}
          </n-button>
        </n-space>
      </n-space>
    </div>

    <!-- 标签页内容 -->
    <n-tabs v-model:value="activeTab" type="line" animated>
      <!-- 详情标签页 -->
      <n-tab-pane name="detail" :tab="t('Detail')">
          <!-- 基本信息 -->
        <n-card :title="t('Basic Information')">
          <div class="properties-grid">
            <div class="property-group">
              <div class="property-item">
                <label>{{ t('Name') }}</label>
                <input type="text" v-model="agentForm.agent_name" />
              </div>
              <div class="property-item">
                <label>{{ t('Status') }}</label>
                <n-select v-model:value="agentForm.status" :options="statusOptions" clearable/>
              </div>
              <div class="property-item">
                <label>{{ t('Enabled') }}</label>
                <n-select v-model:value="agentForm.enabled" :options="enabledOptions" clearable/>
              </div>
              <div class="property-item">
                <label>{{ t('Progress') }}</label>
                <input type="number" v-model="agentForm.progress" min="0" max="100" />
              </div>
            </div>
            <div class="property-group">
              <div class="property-item">
                <label>{{ t('Executions') }}</label>
                <input type="number" v-model="agentForm.ai_repeat" min="0" />
              </div>
              <div class="property-item">
                <label>{{ t('Trigger Mode') }}</label>
                <n-select v-model:value="agentForm.trigger_mode" :options="triggerModeOptions" clearable/>
              </div>
              <div v-if="agentForm.trigger_mode === 'Scheduled Trigger'" class="property-item">
                <label>{{ t('Trigger Time') }}</label>
                <CronEditor v-model="agentForm.trigger_time" />
              </div>
              <div class="property-item">
                <label>{{ t('Created At') }}</label>
                <input type="text" v-model="agentForm.creation" readonly />
              </div>
              <div class="property-item">
                <label>{{ t('Updated At') }}</label>
                <input type="text" v-model="agentForm.modified" readonly />
              </div>
            </div>
          </div>
        </n-card>
      </n-tab-pane>

      <!-- 流程标签页 -->
      <n-tab-pane name="flow" :tab="t('Flow')">
        <n-card :title="t('Agent Flow')">
          <div class="flow-content">
            <textarea 
              v-model="agentForm.agent_flow" 
              class="flow-textarea"
              rows="15"
            />
          </div>
        </n-card>
      </n-tab-pane>

      <!-- 排除关键词标签页 -->
      <n-tab-pane name="exclude" :tab="t('Exclude Keywords')">
        <n-card :title="t('Exclude Keywords')">
          <div class="exclude-content">
            <textarea 
              v-model="agentForm.exclude_prompts" 
              class="exclude-textarea"
              rows="8"
            />
          </div>
        </n-card>
      </n-tab-pane>
    </n-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  NSpace,
  NButton,
  NIcon,
  NCard,
  NSelect,
  NTabs,
  NTabPane,
  useMessage
} from 'naive-ui'
import { Icon } from '@iconify/vue'
import { useFlowBuilderStore } from '../../shared/stores/flowBuilder'
import { useAgentStore } from '../../shared/stores/agent'
import { type AIAgent } from '../../shared/types/agent'
import { t } from '../../shared/i18n'
import CronEditor from '../../core/components/form/controls/CronEditor.vue'

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

// 响应式数据
const agent = ref<AIAgent | null>(null)
const loading = ref(false)
const saving = ref(false)
const executing = ref(false)
const activeTab = ref('detail')

// 表单数据
const agentForm = ref({
  agent_name: '',
  status: '草稿',
  enabled: '1',
  progress: 0,
  ai_repeat: 0,
  trigger_mode: '',
  trigger_time: '* * * * *',
  agent_flow: '',
  exclude_prompts: '',
  creation: '',
  modified: ''
})

// 动态选项
const statusOptions = ref<{ label: string; value: string }[]>([])
const enabledOptions = ref<{ label: string; value: string }[]>([])
const triggerModeOptions = ref<{ label: string; value: string }[]>([])

// 加载选项
const loadOptions = async () => {
  try {
    const { getAgentStatusOptions, getAgentTriggerModeOptions } = await import('@/shared/api/agents')
    const { getFieldSelectOptions } = await import('@/shared/api/common')
    
    // 并行加载所有选项
    const [statusData, enabledData, triggerData] = await Promise.all([
      getAgentStatusOptions(),
      getFieldSelectOptions('Local Ai Agent', 'enabled'),
      getAgentTriggerModeOptions()
    ])
    
    statusOptions.value = statusData.map(option => ({
      label: t(option),
      value: option
    }))
    
    enabledOptions.value = enabledData.map(option => ({
      label: t(option),
      value: option
    }))
    
    triggerModeOptions.value = triggerData.map(option => ({
      label: t(option),
      value: option
    }))
  } catch (error) {
    console.error('Failed to load options:', error)
  }
}

// 计算属性
const agentId = computed(() => route.params.id as string)
const isNew = computed(() => agentId.value === 'new' || agentId.value === '')

// 是否可以执行（参考 Jingrow 逻辑：enabled 且 status 为待执行）
const canExecute = computed(() => {
  if (!agent.value) return false
  const enabled = agent.value.enabled
  const status = agent.value.status
  return enabled && (status === '待执行' || status === '草稿')
})

// 保存智能体
const handleSave = async () => {
  saving.value = true
  try {
    if (isNew.value) {
      // 创建新智能体
      const { createAgent } = await import('@/shared/api/agents')
      const result = await createAgent(agentForm.value)
    if (result.success) {
        message.success(t('Agent created successfully'))
        // 跳转到新创建的智能体详情页
        const created = result?.data ?? result
        const newName = created?.name ?? created?.data?.name ?? created?.message?.name
        if (newName) {
          router.push({ name: 'AgentDetail', params: { id: newName } })
        } else {
          router.push({ name: 'AgentList' })
        }
      } else {
        message.error(t('Create failed') + ': ' + (result.message || t('Unknown error')))
      }
    } else {
      // 更新现有智能体
      const { updateAgent } = await import('@/shared/api/agents')
      const result = await updateAgent(agentId.value, agentForm.value)

      if (result.success) {
        message.success(t('Agent updated successfully'))
        
        await fetchAgent()
      } else {
        message.error(t('Update failed') + ': ' + (result.message || t('Unknown error')))
      }
    }
  } catch (error: any) {
    console.error('Save error:', error)
    message.error(t('Save failed') + ': ' + (error.message || error))
  } finally {
    saving.value = false
  }
}

const handleFlowBuilder = () => {
  let flowData = agent.value?.agent_flow || {}
  if (typeof flowData === 'string') {
    try { flowData = JSON.parse(flowData) } catch (e) { flowData = {} }
  }
  const agentId = agent.value?.name || ''
  flowBuilderStore.activateFlowBuilder(flowData, agentId)
  router.push({ name: 'FlowBuilder', query: { agentId } })
}

// 执行智能体（参考 Jingrow 的异步执行逻辑）
const handleExecute = async () => {
  if (!agentId.value || !agent.value) {
    message.warning(t('Please select agent first'))
    return
  }

  try {
    executing.value = true
    
    // 调用后端异步执行接口
    const response = await fetch('/jingrow/agents/execute', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        agent_id: agentId.value,
        agent_name: agent.value.agent_name,
        session_cookie: document.cookie.split('; ').find(row => row.startsWith('sid='))?.split('=')[1]
      })
    })

    const result = await response.json()
    
    if (result.success) {
      message.success(t('Agent execution started successfully'))
      // 刷新智能体状态
      await fetchAgent()
    } else {
      message.error(result.message || t('Execution failed'))
    }
  } catch (error: any) {
    message.error(error?.message || t('Execution failed'))
  } finally {
    executing.value = false
  }
}

const fetchAgent = async () => {
  if (!agentId.value || isNew.value) return
  
  loading.value = true
  try {
    await agentStore.fetchAgent(agentId.value)
    agent.value = agentStore.currentAgent
    
    // 更新表单数据
    if (agent.value) {
      agentForm.value = {
        agent_name: agent.value.agent_name || '',
        status: agent.value.status || '草稿',
        enabled: String(agent.value.enabled ? 1 : 0),
        progress: agent.value.progress || 0,
        ai_repeat: agent.value.ai_repeat || 0,
        trigger_mode: agent.value.trigger_mode || '',
        trigger_time: agent.value.trigger_time || '* * * * *',
        agent_flow: agent.value.agent_flow ? (typeof agent.value.agent_flow === 'string' ? agent.value.agent_flow : JSON.stringify(agent.value.agent_flow, null, 2)) : '',
        exclude_prompts: agent.value.exclude_prompts || '',
        creation: agent.value.creation || '',
        modified: agent.value.modified || ''
      }
    }
  } catch (error) {
    message.error(t('Failed to load agent detail'))
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadOptions()
  fetchAgent()
})

// 监听路由变化
watch(() => route.params.id, (newId, oldId) => {
  if (newId && newId !== oldId) {
    fetchAgent()
  }
})
</script>

<style scoped>
.agent-detail-page {
  width: 100%;
}
.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-content { background-color: #f8f9fa; border-radius: 6px; padding: 16px; border: 1px solid #e9ecef; }
.flow-json { margin: 0; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 12px; line-height: 1.5; color: #495057; white-space: pre-wrap; word-break: break-all; max-height: 500px; overflow-y: auto; }
.exclude-content { background-color: #f8f9fa; border-radius: 6px; padding: 16px; border: 1px solid #e9ecef; min-height: 100px; }

/* 表单样式 */
.properties-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.property-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.property-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.property-item label {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.property-item input,
.property-item textarea {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.property-item input:focus,
.property-item textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.property-item input[readonly] {
  background-color: #f9fafb;
  color: #6b7280;
}

.flow-textarea,
.exclude-textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s;
  resize: vertical;
  box-sizing: border-box;
}

.flow-textarea:focus,
.exclude-textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
</style>

