<!-- 已安装应用页面 -->
<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>

  </div>
</template>

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

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

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

// 表格列配置
const columns: DataTableColumns = [
  {
    title: t('App Name'),
    key: 'name',
    width: 200
  },
  {
    title: t('Version'),
    key: 'version',
    width: 100,
    render: (row: any) => row.version || '1.0.0'
  },
  {
    title: t('Git Branch'),
    key: 'git_branch',
    width: 120,
    render: (row: any) => row.git_branch || 'main'
  },
  {
    title: t('Actions'),
    key: 'actions',
    width: 280,
    render: (row: any) => {
      return h('div', { class: 'action-buttons' }, [
        h(NButton, {
          size: 'small',
          type: 'default',
          loading: exporting.value === row.name,
          disabled: row.name === 'jingrow',
          onClick: () => exportApp(row)
        }, { default: () => t('Export Package') }),
        h(NButton, {
          size: 'small',
          type: 'error',
          style: 'margin-left: 8px;',
          disabled: !row.uninstallable,
          onClick: () => uninstallApp(row)
        }, { default: () => row.uninstallable ? t('Uninstall') : t('System App') })
      ])
    }
  }
]

// 方法
const loadInstalledApps = async () => {
  try {
    loadingApps.value = true
    
    const response = await axios.get('/jingrow/installed-apps')
    
    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 exportApp = async (app: any) => {
  // 检查是否为系统应用
  if (app.name === 'jingrow') {
    message.warning(t('System App') + ' ' + t('cannot be exported'))
    return
  }
  
  try {
    exporting.value = app.name
    
    const response = await axios.post(`/jingrow/export-app-package/${app.name}`, {})
    
    if (response.data.success) {
      message.success(t('App package exported successfully: {0}').replace('{0}', response.data.filename || app.name))
      // 自动下载文件
      if (response.data.filename) {
        const fileUrl = `/files/${response.data.filename}`
        window.open(fileUrl, '_blank')
      }
    } else {
      message.error(response.data.error || t('Failed to export app package'))
    }
  } catch (error: any) {
    console.error('Export app error:', error)
    message.error(error.response?.data?.error || t('Failed to export app package'))
  } finally {
    exporting.value = null
  }
}

const uninstallApp = async (app: any) => {
  // 检查是否为系统应用
  if (!app.uninstallable) {
    message.warning(t('System App') + ' ' + t('cannot be uninstalled'))
    return
  }
  
  dialog.warning({
    title: t('Uninstall App'),
    content: t('Are you sure you want to uninstall \'{0}\'? This action cannot be undone.').replace('{0}', app.name),
    positiveText: t('Uninstall'),
    negativeText: t('Cancel'),
    onPositiveClick: async () => {
      try {
        uninstalling.value = true
        
        const response = await axios.post(`/jingrow/uninstall/${app.name}`, {})
        
        if (response.data.success) {
          message.success(t('App \'{0}\' uninstalled successfully').replace('{0}', app.name))
          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
      }
    }
  })
}


// 生命周期
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>
