<template>
  <div class="agent-detail">
    <div class="page-header">
      <div class="header-content">
        <div class="header-text">
          <h1>{{ agent?.title || agent?.agent_name || t('Agent Details') }}</h1>
        </div>
        <div class="header-actions">
          <n-button @click="goBack" size="medium">
            <template #icon>
              <n-icon><Icon icon="tabler:arrow-left" /></n-icon>
            </template>
            {{ t('Back') }}
          </n-button>
          <n-button 
            :type="isCurrentAgentInstalled ? 'warning' : 'primary'" 
            @click="installAgent" 
            size="medium"
          >
            <template #icon>
              <n-icon>
                <Icon :icon="isCurrentAgentInstalled ? 'tabler:check' : 'tabler:download'" />
              </n-icon>
            </template>
            {{ isCurrentAgentInstalled ? t('Installed') : t('Install') }}
          </n-button>
        </div>
      </div>
    </div>

    <div v-if="loading" class="loading-container">
      <n-spin size="large">
        <template #description>
          {{ t('Loading agent details...') }}
        </template>
      </n-spin>
    </div>

    <div v-else-if="error" class="error-container">
      <n-empty :description="error">
        <template #icon>
          <n-icon><Icon icon="tabler:alert-circle" /></n-icon>
        </template>
      </n-empty>
    </div>

    <div v-else-if="agent" class="agent-content">
      <!-- 整体卡片布局 -->
      <div class="agent-card">
        <!-- 上部分：智能体信息 -->
        <div class="agent-info-section">
          <div class="agent-content-layout">
            <!-- 左侧：智能体图标 -->
            <div class="agent-image-section">
              <div class="agent-image">
                <div v-if="agent.icon" class="agent-icon-container">
                  <Icon 
                    :icon="agent.icon" 
                    :width="120" 
                    :height="120"
                    :style="{ color: agent.color || '#6b7280' }"
                  />
                </div>
                <div v-else class="placeholder-image">
                  <n-icon size="80"><Icon icon="hugeicons:robotic" /></n-icon>
                </div>
              </div>
            </div>
            
            <!-- 右侧：智能体信息 -->
            <div class="agent-info-content">
              <div class="agent-header">
                <h2 class="agent-title">{{ agent.title || agent.agent_name || t('Untitled Agent') }}</h2>
                <div v-if="agent.subtitle" class="agent-subtitle">{{ agent.subtitle }}</div>
              </div>
              
              <div class="info-list">
                <div v-if="agent.agent_name" class="info-item">
                  <span class="label">{{ t('Agent Name') }}:</span>
                  <span class="value">{{ agent.agent_name }}</span>
                </div>
                
                <div v-if="agent.status" class="info-item">
                  <span class="label">{{ t('Status') }}:</span>
                  <span class="value">{{ agent.status }}</span>
                </div>
                
                <div v-if="agent.trigger_mode" class="info-item">
                  <span class="label">{{ t('Trigger Mode') }}:</span>
                  <span class="value">{{ agent.trigger_mode }}</span>
                </div>
                
                <div v-if="agent.creation" class="info-item">
                  <span class="label">{{ t('Created') }}:</span>
                  <span class="value">{{ formatDate(agent.creation) }}</span>
                </div>
                
                <div v-if="agent.modified" class="info-item">
                  <span class="label">{{ t('Last Updated') }}:</span>
                  <span class="value">{{ formatDate(agent.modified) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 下部分：描述内容 -->
        <div v-if="agent.description" class="description-section">
          <h3>{{ t('Description') }}</h3>
          <div class="description-content" v-html="agent.description"></div>
        </div>

      </div>
    </div>
    
    <!-- 安装进度弹窗 -->
    <InstallProgressModal
      v-model="showProgressModal"
      :progress="installProgress"
      :message="installMessage"
      :status="installStatus"
      :installing="installing"
      :title="t('Installing Agent')"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { NButton, NIcon, NSpin, NEmpty, useMessage, useDialog } from 'naive-ui'
import { Icon } from '@iconify/vue'
import axios from 'axios'
import { t } from '@/shared/i18n'
import InstallProgressModal from './InstallProgressModal.vue'

const route = useRoute()
const router = useRouter()
const message = useMessage()
const dialog = useDialog()

const loading = ref(true)
const error = ref('')
const agent = ref<any>(null)

// 安装相关状态
const installing = ref(false)
const installProgress = ref(0)
const installMessage = ref('')
const installStatus = ref<'success' | 'error' | 'info'>('info')
const showProgressModal = ref(false)

// 已安装智能体集合
const installedAgentNames = ref<Set<string>>(new Set())

const agentName = computed(() => route.params.name as string)

// 检查当前智能体是否已安装
const isCurrentAgentInstalled = computed(() => {
  if (!agent.value) return false
  return isAgentInstalled(agent.value.agent_name || agent.value.name || '')
})

async function loadAgentDetail() {
  loading.value = true
  error.value = ''
  
  try {
    const response = await axios.get(`/jingrow/agent-marketplace/${agentName.value}`)
    agent.value = response.data
  } catch (err: any) {
    console.error('Failed to load agent detail:', err)
    error.value = err.response?.data?.detail || t('Failed to load agent details')
  } finally {
    loading.value = false
  }
}

function formatDate(dateString: string): string {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

function goBack() {
  // 从查询参数获取返回路径
  const returnTo = route.query.returnTo as string
  if (returnTo) {
    router.push(returnTo)
    return
  }
  
  // 检查路由历史
  if (window.history.length > 1) {
    router.back()
  } else {
    // 默认返回智能体市场
    router.push('/agent-marketplace')
  }
}

async function installAgent() {
  if (!agent.value?.agent_flow && !agent.value?.agent_name) {
    message.error(t('Agent flow data or name is missing'))
    return
  }
  
  // 先检查智能体是否已存在
  try {
    const agentNameValue = agent.value.agent_name || agent.value.name
    if (agentNameValue) {
      const checkResponse = await axios.get(`/jingrow/check-agent/${agentNameValue}`)
      
      if (checkResponse.data.exists) {
        // 显示确认对话框
        dialog.warning({
          title: t('Agent already exists'),
          content: t('Agent "{0}" is already installed, do you want to overwrite?').replace('{0}', agentNameValue),
          positiveText: t('Confirm Overwrite'),
          negativeText: t('Cancel'),
          onPositiveClick: () => {
            performInstall()
          }
        })
        return
      }
    }
  } catch (error) {
    console.error('Check agent exists error:', error)
  }
  
  performInstall()
}

async function performInstall() {
  try {
    installing.value = true
    installProgress.value = 0
    installMessage.value = t('Preparing installation...')
    installStatus.value = 'info'
    showProgressModal.value = true
    
    // 获取流程数据和名称
    let agentFlow = agent.value.agent_flow
    let agentNameValue = agent.value.agent_name || agent.value.name
    
    if (!agentFlow) {
      throw new Error(t('Agent flow data is missing'))
    }
    
    installProgress.value = 30
    installMessage.value = t('Installing agent...')
    
    // 如果 agent_flow 是字符串，尝试解析为 JSON
    if (typeof agentFlow === 'string') {
      try {
        agentFlow = JSON.parse(agentFlow)
      } catch (e) {
        // 如果解析失败，保持原样
      }
    }
    
    const response = await axios.post('/jingrow/install-agent', {
      agent_name: agentNameValue,
      agent_flow: agentFlow
    }, {
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    // 更新进度到安装完成
    installProgress.value = 100
    
    if (response.data.success) {
      // 所有步骤完成后才显示成功
      installing.value = false
      installStatus.value = 'success'
      installMessage.value = t('Agent installed successfully!')
      message.success(t('Agent installed successfully'))
      
      // 刷新已安装智能体列表
      loadInstalledAgents()
      
      setTimeout(() => {
        showProgressModal.value = false
      }, 2000)
    } else {
      throw new Error(response.data.error || t('安装失败'))
    }
  } catch (error: any) {
    console.error('Install agent error:', error)
    installing.value = false
    installStatus.value = 'error'
    installMessage.value = error.response?.data?.detail || error.message || t('Installation failed')
    message.error(error.response?.data?.detail || t('Installation failed'))
    
    setTimeout(() => {
      showProgressModal.value = false
    }, 3000)
  }
}

// 加载已安装智能体列表
async function loadInstalledAgents() {
  try {
    const response = await axios.get('/jingrow/installed-agent-names')
    if (response.data.success) {
      const agents = response.data.agents || []
      installedAgentNames.value = new Set(agents.map((a: string) => a.toLowerCase()))
    }
  } catch (error) {
    console.error('Load installed agents error:', error)
  }
}

// 检查智能体是否已安装
function isAgentInstalled(agentNameValue: string): boolean {
  if (!agentNameValue) return false
  return installedAgentNames.value.has(agentNameValue.toLowerCase())
}

onMounted(() => {
  loadAgentDetail()
  loadInstalledAgents()
  
  // 监听全局事件
  window.addEventListener('installedAgentsUpdated', () => {
    loadInstalledAgents()
  })
})
</script>

<style scoped>
.agent-detail {
  padding: 24px;
}

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

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 30px;
}

.header-text h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 700;
  color: #1a1a1a;
}

.header-text p {
  margin: 0;
  color: #666;
  font-size: 16px;
}

.loading-container,
.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.agent-content {
  display: flex;
  flex-direction: column;
  gap: 32px;
}

/* 整体卡片布局 */
.agent-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 上部分：智能体信息 */

.agent-content-layout {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 50px;
  align-items: start;
}

.agent-image-section {
  display: flex;
  justify-content: center;
  align-items: center;
}

.agent-image {
  width: 100%;
  min-height: 300px;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.agent-icon-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.placeholder-image {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #9ca3af;
}

.agent-header {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e5e7eb;
}

.agent-title {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #1a1a1a;
}

.agent-subtitle {
  margin: 8px 0 0 0;
  font-size: 14px;
  color: #6b7280;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.info-item .label {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
  min-width: 80px;
}

.info-item .value {
  color: #6b7280;
  font-size: 14px;
}

.link {
  color: #2563eb;
  text-decoration: none;
}

.link:hover {
  text-decoration: underline;
}

.text-muted {
  color: #9ca3af;
  font-style: italic;
}

/* 下部分：描述内容 */
.description-section {
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.description-section h3 {
  margin: 0 0 20px 0;
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
}

.description-content {
  color: #374151;
  line-height: 1.6;
}

.description-content :deep(h1),
.description-content :deep(h2),
.description-content :deep(h3),
.description-content :deep(h4),
.description-content :deep(h5),
.description-content :deep(h6) {
  margin: 16px 0 8px 0;
  color: #1f2937;
}

.description-content :deep(p) {
  margin: 8px 0;
}

.description-content :deep(ul),
.description-content :deep(ol) {
  margin: 8px 0;
  padding-left: 20px;
}

.description-content :deep(li) {
  margin: 4px 0;
}

.description-content :deep(code) {
  background: #f3f4f6;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 14px;
}

.description-content :deep(pre) {
  background: #f3f4f6;
  padding: 16px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 16px 0;
}

.description-content :deep(blockquote) {
  border-left: 4px solid #e5e7eb;
  padding-left: 16px;
  margin: 16px 0;
  color: #6b7280;
  font-style: italic;
}

@media (max-width: 768px) {
  .agent-card {
    padding: 20px;
  }
  
  .agent-content-layout {
    grid-template-columns: 1fr;
    gap: 30px;
  }
  
  .agent-image-section {
    order: 2;
    justify-content: center;
  }
  
  .agent-image {
    max-width: 150px;
  }
  
  .agent-title {
    font-size: 20px;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .info-item .label {
    min-width: auto;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
  }
}
</style>

