<template>
  <div class="tool-detail">
    <div class="page-header">
      <div class="header-content">
        <div class="header-text">
          <h1>{{ tool?.title || tool?.name || t('Tool 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="isCurrentToolInstalled ? 'warning' : 'primary'" 
            @click="installTool" 
            size="medium"
          >
            <template #icon>
              <n-icon>
                <Icon :icon="isCurrentToolInstalled ? 'tabler:check' : 'tabler:download'" />
              </n-icon>
            </template>
            {{ isCurrentToolInstalled ? t('Installed') : t('Install') }}
          </n-button>
        </div>
      </div>
    </div>

    <div v-if="loading" class="loading-container">
      <n-spin size="large">
        <template #description>
          {{ t('Loading tool 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="tool" class="tool-content">
      <!-- 整体卡片布局 -->
      <div class="tool-card">
        <!-- 上部分：工具信息 -->
        <div class="tool-info-section">
          <div class="tool-content-layout">
            <!-- 左侧：工具图片 -->
            <div class="tool-image-section">
              <div class="tool-image">
                <img 
                  v-if="tool.tool_image" 
                  :src="getImageUrl(tool.tool_image)" 
                  :alt="tool.title || tool.name"
                  @error="handleImageError"
                />
                <div v-else class="placeholder-image">
                  <n-icon size="80"><Icon icon="tabler:tool" /></n-icon>
                </div>
              </div>
            </div>
            
            <!-- 右侧：工具信息 -->
            <div class="tool-info-content">
              <div class="tool-header">
                <h2 class="tool-title">{{ tool.title || tool.name || t('Untitled Tool') }}</h2>
                <div v-if="tool.subtitle" class="tool-subtitle">{{ tool.subtitle }}</div>
              </div>
              
              <div class="info-list">
                <div v-if="tool.tool_name" class="info-item">
                  <span class="label">{{ t('Tool Name') }}:</span>
                  <span class="value">{{ tool.tool_name }}</span>
                </div>
                
                <div v-if="tool.team" class="info-item">
                  <span class="label">{{ t('Developer') }}:</span>
                  <span class="value">{{ tool.team }}</span>
                </div>
                
                <div v-if="tool.version" class="info-item">
                  <span class="label">{{ t('Version') }}:</span>
                  <span class="value">{{ tool.version }}</span>
                </div>
                
                <div v-if="tool.type" class="info-item">
                  <span class="label">{{ t('Type') }}:</span>
                  <span class="value">{{ tool.type }}</span>
                </div>
                
                <div v-if="tool.route_name" class="info-item">
                  <span class="label">{{ t('Route Name') }}:</span>
                  <span class="value">{{ tool.route_name }}</span>
                </div>
                
                <div v-if="tool.url" class="info-item">
                  <span class="label">{{ t('URL') }}:</span>
                  <a :href="tool.url" target="_blank" class="link">
                    {{ tool.url }}
                  </a>
                </div>
                
                <div v-if="tool.creation" class="info-item">
                  <span class="label">{{ t('Created') }}:</span>
                  <span class="value">{{ formatDate(tool.creation) }}</span>
                </div>
                
                <div v-if="tool.modified" class="info-item">
                  <span class="label">{{ t('Last Updated') }}:</span>
                  <span class="value">{{ formatDate(tool.modified) }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

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

      </div>
    </div>
    
    <!-- 安装进度弹窗 -->
    <InstallProgressModal
      v-model="showProgressModal"
      :progress="installProgress"
      :message="installMessage"
      :status="installStatus"
      :installing="installing"
    />
  </div>
</template>

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

const route = useRoute()
const router = useRouter()
const message = useMessage()
const toolsStore = useToolsStore()

const loading = ref(true)
const error = ref('')
const tool = 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 installedToolNames = ref<Set<string>>(new Set())

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

// 检查当前工具是否已安装
const isCurrentToolInstalled = computed(() => {
  if (!tool.value) return false
  return isToolInstalled(tool.value.name || '')
})

async function loadToolDetail() {
  loading.value = true
  error.value = ''
  
  try {
    const response = await axios.get(`/jingrow/tool-marketplace/${toolName.value}`)
    tool.value = response.data
  } catch (err: any) {
    console.error('Failed to load tool detail:', err)
    error.value = err.response?.data?.detail || t('Failed to load tool 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 getImageUrl(imageUrl: string): string {
  if (!imageUrl) return ''
  if (imageUrl.startsWith('http')) {
    return imageUrl
  }
  // 使用云端URL拼接
  const cloudUrl = 'https://cloud.jingrow.com'
  return `${cloudUrl}${imageUrl.startsWith('/') ? '' : '/'}${imageUrl}`
}

function handleImageError(event: Event) {
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
  const placeholder = img.parentElement?.querySelector('.placeholder-image') as HTMLElement
  if (placeholder) {
    placeholder.style.display = 'flex'
  }
}

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('/tool-marketplace')
  }
}

async function installTool() {
  if (!tool.value.file_url && !tool.value.repository_url) {
    message.error(t('工具文件URL或仓库地址不存在'))
    return
  }
  
  performInstall()
}

async function performInstall() {
  try {
    installing.value = true
    installProgress.value = 0
    installMessage.value = t('正在准备安装...')
    installStatus.value = 'info'
    showProgressModal.value = true
    
    let response
    
    // 优先使用文件URL，否则使用git仓库
    if (tool.value.file_url) {
      installMessage.value = t('正在下载工具包...')
      installProgress.value = 20
      
      installMessage.value = t('正在安装工具...')
      installProgress.value = 30
      
      response = await axios.post('/jingrow/install-tool-from-url', new URLSearchParams({
        tool_name: tool.value.name || tool.value.tool_name,
        url: tool.value.file_url
      }), {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })
    } else if (tool.value.repository_url) {
      installMessage.value = t('正在克隆仓库...')
      installProgress.value = 20
      
      installMessage.value = t('正在安装工具...')
      installProgress.value = 30
      
      // 注意：目前后端可能还没有 install-tool-from-git API，需要检查
      message.warning(t('从Git仓库安装工具功能暂未实现'))
      installing.value = false
      installStatus.value = 'error'
      installMessage.value = t('从Git仓库安装工具功能暂未实现')
      setTimeout(() => {
        showProgressModal.value = false
      }, 3000)
      return
    }
    
    if (!response) {
      throw new Error(t('无法确定安装方式'))
    }
    
    // 更新进度到安装完成
    installProgress.value = 100
    
    if (response.data.success) {
      // 所有步骤完成后才显示成功
      installing.value = false
      installStatus.value = 'success'
      installMessage.value = t('工具安装成功！')
      message.success(t('工具安装成功'))
      
      // 将工具添加到 toolsStore
      // 重要：tool_name 是实际的工具名称（用于文件夹），tool.value.name 是市场的唯一ID
      const toolName = response.data.tool_name || tool.value.tool_name  // 实际的 tool_name（用于文件夹）
      const toolTitle = response.data.tool_title || tool.value.title || tool.value.name
      const marketplaceId = tool.value.name  // 市场的唯一ID（用于识别）
      
      if (!toolName) {
        console.error('无法获取工具名称 (tool_name)')
        throw new Error('无法获取工具名称')
      }
      
      // 检查工具是否已存在于 store 中（使用市场的唯一ID检查）
      const existingTool = toolsStore.userTools.find(
        t => t.marketplaceId === marketplaceId && t.fromMarketplace
      )
      
      if (!existingTool) {
        // 构建工具数据
        const toolData = {
          id: marketplaceId || `tool-${Date.now()}`,  // 使用市场唯一ID作为id
          name: toolTitle,
          description: tool.value.description,
          category: tool.value.category,
          icon: tool.value.icon,
          color: tool.value.color || undefined, // 如果为空，不设置默认值，使用 undefined
          type: 'route' as const,
          routeName: tool.value.route_name, // 可能不存在，会在 addUserTool 中自动生成
          isDefault: false,
          fromMarketplace: true,
          marketplaceId: marketplaceId,  // 市场的唯一ID
          toolName: toolName,  // 实际的 tool_name（用于删除文件）
          componentPath: `tools/${toolName}/${toolName}.vue` // 组件路径使用实际的 tool_name
        }
        
        // 添加到 store 并注册路由
        toolsStore.addUserTool(toolData, router, toolData.componentPath)
      }
      
      // 刷新已安装工具列表
      loadInstalledTools()
      
      // 触发全局事件，通知工具列表页刷新
      if (typeof window !== 'undefined') {
        window.dispatchEvent(new Event('installedToolsUpdated'))
      }
      
      setTimeout(() => {
        showProgressModal.value = false
      }, 2000)
    } else {
      throw new Error(response.data.error || t('安装失败'))
    }
  } catch (error: any) {
    console.error('Install tool error:', error)
    installing.value = false
    installStatus.value = 'error'
    installMessage.value = error.response?.data?.detail || error.message || t('安装失败')
    message.error(error.response?.data?.detail || t('安装失败'))
    
    setTimeout(() => {
      showProgressModal.value = false
    }, 3000)
  }
}

// 加载已安装工具列表
async function loadInstalledTools() {
  try {
    const userTools = toolsStore.userTools
    // 存储为小写以便不区分大小写匹配
    installedToolNames.value = new Set(
      userTools
        .filter(t => t.fromMarketplace && t.marketplaceId)
        .map(t => (t.marketplaceId || t.name).toLowerCase())
    )
  } catch (error) {
    console.error('Load installed tools error:', error)
  }
}

// 检查工具是否已安装
function isToolInstalled(toolName: string): boolean {
  if (!toolName) return false
  return installedToolNames.value.has(toolName.toLowerCase())
}

onMounted(() => {
  loadToolDetail()
  loadInstalledTools()
  
  // 监听全局事件
  window.addEventListener('installedToolsUpdated', () => {
    loadInstalledTools()
  })
})
</script>

<style scoped>
.tool-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;
}

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

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

.tool-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;
}

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

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

.tool-image {
  width: 100%;
  min-height: 300px;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f9fafb;
  position: relative;
}

.tool-image img {
  width: 100%;
  height: 100%;
  min-height: 300px;
  object-fit: cover;
  display: block;
  position: absolute;
  top: 0;
  left: 0;
}

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

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

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

.tool-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;
}

.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) {
  .tool-card {
    padding: 20px;
  }
  
  .tool-content-layout {
    grid-template-columns: 1fr;
    gap: 30px;
  }
  
  .tool-image-section {
    order: 2;
    justify-content: center;
  }
  
  .tool-image {
    max-width: 150px;
  }
  
  .tool-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>

