<!-- 已安装应用页面 -->
<template>
  <div class="installed-apps-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <n-icon><Icon icon="tabler:apps" /></n-icon>
          {{ t('Installed Apps') }}
        </h1>
        <p class="page-description">{{ t('Manage your locally installed applications') }}</p>
      </div>
    </div>

    <!-- 应用列表 -->
    <div class="apps-section">
      <n-card class="apps-card">
        <template #header-extra>
          <n-button @click="refreshApps" :loading="loadingApps">
            <template #icon>
              <n-icon><Icon icon="tabler:refresh" /></n-icon>
            </template>
            {{ t('Refresh') }}
          </n-button>
        </template>
        
        <n-data-table
          :columns="columns"
          :data="installedApps"
          :loading="loadingApps"
          :pagination="false"
        />
      </n-card>
    </div>

    <!-- 应用详情模态框 -->
    <n-modal v-model:show="showDetailModal" preset="card" style="width: 600px">
      <template #header>
        <h3>{{ selectedApp?.name || t('App Details') }}</h3>
      </template>
      
      <div v-if="selectedApp" class="app-detail">
        <n-descriptions :column="1" bordered>
          <n-descriptions-item :label="t('App Name')">
            {{ selectedApp.name }}
          </n-descriptions-item>
          <n-descriptions-item :label="t('Type')">
            {{ getAppTypeText(selectedApp.type) }}
          </n-descriptions-item>
          <n-descriptions-item :label="t('Backend Path')">
            {{ selectedApp.path || t('Not installed') }}
          </n-descriptions-item>
          <n-descriptions-item :label="t('Frontend Path')">
            {{ selectedApp.frontend_path || t('Not installed') }}
          </n-descriptions-item>
          <n-descriptions-item :label="t('Version')">
            {{ selectedApp.version || t('Unknown') }}
          </n-descriptions-item>
          <n-descriptions-item :label="t('Description')">
            {{ selectedApp.description || t('No description') }}
          </n-descriptions-item>
        </n-descriptions>
      </div>
      
      <template #action>
        <n-space>
          <n-button @click="showDetailModal = false">{{ t('Close') }}</n-button>
          <n-button type="error" @click="uninstallApp(selectedApp)" :loading="uninstalling">
            {{ t('Uninstall') }}
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, h } from 'vue'
import {
  NIcon, NButton, NSpace, NCard, NDataTable, NModal, 
  NDescriptions, NDescriptionsItem, useMessage, useDialog, 
  type DataTableColumns
} from 'naive-ui'
import { Icon } from '@iconify/vue'
import axios from 'axios'
import { get_session_api_headers } from '@/shared/api/auth'
import { t } from '@/shared/i18n'

// 响应式数据
const installedApps = ref<any[]>([])
const loadingApps = ref(false)
const showDetailModal = ref(false)
const selectedApp = ref<any>(null)
const uninstalling = ref(false)

const message = useMessage()
const dialog = useDialog()

// 表格列配置
const columns: DataTableColumns = [
  {
    title: t('App Name'),
    key: 'name',
    width: 200
  },
  {
    title: t('Type'),
    key: 'type',
    width: 120,
    render: (row: any) => getAppTypeText(row.type)
  },
  {
    title: t('Backend Path'),
    key: 'path',
    ellipsis: true,
    render: (row: any) => row.path || t('Not installed')
  },
  {
    title: t('Frontend Path'),
    key: 'frontend_path',
    ellipsis: true,
    render: (row: any) => row.frontend_path || t('Not installed')
  },
  {
    title: t('Actions'),
    key: 'actions',
    width: 150,
    render: (row: any) => {
      return h('div', { class: 'action-buttons' }, [
        h(NButton, {
          size: 'small',
          onClick: () => showAppDetail(row)
        }, { default: () => t('Details') }),
        h(NButton, {
          size: 'small',
          type: 'error',
          onClick: () => uninstallApp(row)
        }, { default: () => t('Uninstall') })
      ])
    }
  }
]

// 方法
const loadInstalledApps = async () => {
  try {
    loadingApps.value = true
    
    const response = await axios.get('/jingrow/installed-apps', {
      headers: get_session_api_headers()
    })
    
    if (response.data.success) {
      installedApps.value = response.data.data.apps || []
    } else {
      message.error(response.data.error || t('Failed to load apps'))
    }
  } catch (error: any) {
    console.error('Load apps error:', error)
    message.error(error.response?.data?.error || t('Failed to load apps'))
  } finally {
    loadingApps.value = false
  }
}

const refreshApps = () => {
  loadInstalledApps()
}

const showAppDetail = async (app: any) => {
  try {
    const response = await axios.get(`/jingrow/app-info/${app.name}`, {
      headers: get_session_api_headers()
    })
    
    if (response.data.success) {
      selectedApp.value = { ...app, ...response.data.data }
      showDetailModal.value = true
    } else {
      message.error(response.data.error || t('Failed to load app details'))
    }
  } catch (error: any) {
    console.error('Load app detail error:', error)
    message.error(error.response?.data?.error || t('Failed to load app details'))
  }
}

const uninstallApp = async (app: any) => {
  dialog.warning({
    title: t('Uninstall App'),
    content: t(`Are you sure you want to uninstall '${app.name}'? This action cannot be undone.`),
    positiveText: t('Uninstall'),
    negativeText: t('Cancel'),
    onPositiveClick: async () => {
      try {
        uninstalling.value = true
        
        const response = await axios.post(`/jingrow/uninstall/${app.name}`, {}, {
          headers: get_session_api_headers()
        })
        
        if (response.data.success) {
          message.success(t(`App '${app.name}' uninstalled successfully`))
          await loadInstalledApps()
        } else {
          message.error(response.data.error || t('Failed to uninstall app'))
        }
      } catch (error: any) {
        console.error('Uninstall app error:', error)
        message.error(error.response?.data?.error || t('Failed to uninstall app'))
      } finally {
        uninstalling.value = false
      }
    }
  })
}

const getAppTypeText = (type: string) => {
  switch (type) {
    case 'frontend': return t('Frontend Only')
    case 'both': return t('Full Stack')
    default: return t('Backend Only')
  }
}

// 生命周期
onMounted(() => {
  loadInstalledApps()
})
</script>

<style scoped>
.installed-apps-page {
  padding: 16px 24px;
  width: 100%;
  margin: 0;
  min-height: 100vh;
}

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

.header-content {
  text-align: center;
}

.page-title {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
}

.page-description {
  margin: 0;
  color: #6b7280;
  font-size: 16px;
}

.apps-section {
  margin-bottom: 32px;
}

.apps-card {
  background: white;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  overflow: hidden;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.app-detail {
  padding: 16px 0;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .installed-apps-page {
    padding: 12px 16px;
  }
}

@media (max-width: 768px) {
  .installed-apps-page {
    padding: 8px 12px;
  }
  
  .page-header {
    margin-bottom: 16px;
  }
  
  .apps-section {
    margin-top: 16px;
  }
}
</style>
