<!-- Jingrow Local 应用安装页面 -->
<template>
  <div class="app-installer-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <n-icon><Icon icon="tabler:upload" /></n-icon>
          {{ t('App Installer') }}
        </h1>
        <p class="page-description">{{ t('Upload and install applications to your local Jingrow environment') }}</p>
      </div>
    </div>

    <!-- 上传区域 -->
    <div class="upload-section">
      <n-card :title="t('Upload App Package')" class="upload-card">
        <n-upload
          ref="uploadRef"
          :file-list="fileList"
          :max="1"
          accept=".zip"
          :show-file-list="false"
          :on-before-upload="beforeUpload"
          :on-change="handleFileChange"
          :custom-request="customUpload"
          :disabled="uploading"
        >
          <n-upload-dragger>
            <div class="upload-content">
              <n-icon size="48" :depth="3">
                <Icon icon="tabler:cloud-upload" />
              </n-icon>
              <n-text style="font-size: 16px">
                {{ uploading ? t('Uploading...') : t('Click or drag ZIP file to this area to upload') }}
              </n-text>
              <n-p depth="3" style="margin: 8px 0 0 0">
                {{ t('Support for ZIP format only') }}
              </n-p>
            </div>
          </n-upload-dragger>
        </n-upload>
        
        <!-- 应用名称输入 -->
        <div class="app-name-input" v-if="fileList.length > 0">
          <n-form-item :label="t('App Name (Optional)')">
            <n-input
              v-model:value="appName"
              :placeholder="t('Leave empty to auto-detect from package')"
              :disabled="uploading"
            />
          </n-form-item>
        </div>
        
        <!-- 上传按钮 -->
        <div class="upload-actions" v-if="fileList.length > 0">
          <n-space>
            <n-button @click="clearFiles" :disabled="uploading">
              {{ t('Clear') }}
            </n-button>
            <n-button type="primary" @click="startUpload" :loading="uploading" :disabled="uploading">
              <template #icon>
                <n-icon><Icon icon="tabler:upload" /></n-icon>
              </template>
              {{ t('Install App') }}
            </n-button>
          </n-space>
        </div>
      </n-card>
    </div>


    <!-- 本地App列表 -->
    <div class="local-apps-section" v-if="localApps.length > 0">
      <n-card :title="t('Local Apps Available')" class="local-apps-card">
        <n-data-table
          :columns="localAppsColumns"
          :data="localApps"
          :loading="loadingLocalApps"
          :pagination="false"
          :bordered="false"
        />
      </n-card>
    </div>

    <!-- 安装进度模态框 -->
    <n-modal v-model:show="showProgressModal" preset="card" style="width: 500px">
      <template #header>
        <h3>{{ t('Installing App') }}</h3>
      </template>
      
      <div class="progress-content">
        <n-progress
          :percentage="installProgress"
          :status="installStatus"
          :show-indicator="true"
        />
        <n-text class="progress-text">{{ installMessage }}</n-text>
      </div>
      
      <template #action>
        <n-button @click="showProgressModal = false" :disabled="installing">
          {{ installing ? t('Installing...') : t('Close') }}
        </n-button>
      </template>
    </n-modal>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, h } from 'vue'
import {
  NIcon, NButton, NSpace, NCard, NUpload, NUploadDragger, NText, NP,
  NFormItem, NInput, NModal, NProgress, NDataTable, useMessage, type UploadFileInfo, 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 fileList = ref<UploadFileInfo[]>([])
const appName = ref('')
const uploading = ref(false)
const installing = ref(false)
const installProgress = ref(0)
const installMessage = ref('')
const installStatus = ref<'success' | 'error' | 'info'>('info')
const showProgressModal = ref(false)

// 本地App相关
const localApps = ref<any[]>([])
const loadingLocalApps = ref(false)

const message = useMessage()
const uploadRef = ref()

// 本地App表格列定义
const localAppsColumns: DataTableColumns<any> = [
  {
    title: t('App Name'),
    key: 'name',
    width: 150
  },
  {
    title: t('Title'),
    key: 'title',
    width: 200
  },
  {
    title: t('Publisher'),
    key: 'publisher',
    width: 150
  },
  {
    title: t('Description'),
    key: 'description',
    ellipsis: true
  },
  {
    title: t('Actions'),
    key: 'actions',
    width: 120,
    render: (row: any) => {
      return h(NButton, {
        type: 'primary',
        size: 'small',
        onClick: () => installLocalApp(row.name)
      }, {
        default: () => t('Install')
      })
    }
  }
]

// 方法

const beforeUpload = (data: { file: UploadFileInfo }) => {
  const file = data.file.file
  if (!file) return false
  
  if (!file.name.toLowerCase().endsWith('.zip')) {
    message.error(t('Only ZIP files are supported'))
    return false
  }
  
  return true
}

const handleFileChange = (options: { fileList: UploadFileInfo[] }) => {
  fileList.value = options.fileList
}

const customUpload = async (_options: any) => {
  // 这里不做实际上传，只是保存文件信息
  return Promise.resolve()
}

const startUpload = async () => {
  if (fileList.value.length === 0) {
    message.error(t('Please select a file first'))
    return
  }
  
  const file = fileList.value[0].file
  if (!file) {
    message.error(t('File not found'))
    return
  }
  
  try {
    uploading.value = true
    installing.value = true
    showProgressModal.value = true
    installProgress.value = 0
    installMessage.value = t('Preparing upload...')
    installStatus.value = 'info'
    
    // 创建FormData
    const formData = new FormData()
    formData.append('file', file)
    if (appName.value.trim()) {
      formData.append('app_name', appName.value.trim())
    }
    
    installProgress.value = 30
    installMessage.value = t('Uploading file...')
    
    // 上传文件
    const response = await axios.post('/jingrow/install/upload', formData, {
      headers: {
        ...get_session_api_headers(),
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total) {
          const progress = Math.round((progressEvent.loaded * 70) / progressEvent.total) + 30
          installProgress.value = Math.min(progress, 100)
        }
      }
    })
    
    installProgress.value = 100
    installMessage.value = t('Installation completed!')
    installStatus.value = 'success'
    
    if (response.data.success) {
      // 清空文件列表
      clearFiles()
      
      message.success(t('App \'{0}\' installed successfully').replace('{0}', response.data.app_name))
    } else {
      throw new Error(response.data.error || t('Installation failed'))
    }
    
  } catch (error: any) {
    installProgress.value = 100
    installMessage.value = t('Installation failed!')
    installStatus.value = 'error'
    
    console.error('Upload error:', error)
    message.error(error.response?.data?.detail || error.message || t('Upload failed'))
  } finally {
    uploading.value = false
    installing.value = false
  }
}

const clearFiles = () => {
  fileList.value = []
  appName.value = ''
  uploadRef.value?.clear()
}

// 本地App相关方法
const loadLocalApps = async () => {
  loadingLocalApps.value = true
  try {
    const base = (import.meta as any).env.VITE_LOCAL_API_URL || ''
    const response = await axios.get(`${base}/jingrow/local-apps`, {
      headers: get_session_api_headers(),
      withCredentials: true
    })
    
    if (response.data.success) {
      localApps.value = response.data.data.apps
    } else {
      message.error(response.data.detail || t('Failed to load local apps'))
    }
  } catch (error: any) {
    console.error('Load local apps error:', error)
    message.error(error?.response?.data?.detail || error?.message || t('Failed to load local apps'))
  } finally {
    loadingLocalApps.value = false
  }
}

const installLocalApp = async (appName: string) => {
  try {
    const base = (import.meta as any).env.VITE_LOCAL_API_URL || ''
    const response = await axios.post(`${base}/jingrow/install-local/${appName}`, {}, {
      headers: get_session_api_headers(),
      withCredentials: true
    })
    
    if (response.data.success) {
      message.success(t('App \'{0}\' installed successfully').replace('{0}', appName))
      // 重新加载本地App列表
      await loadLocalApps()
    } else {
      message.error(response.data.detail || t('Failed to install app'))
    }
  } catch (error: any) {
    console.error('Install local app error:', error)
    message.error(error?.response?.data?.detail || error?.message || t('Failed to install app'))
  }
}

// 生命周期
onMounted(() => {
  // 加载本地App列表
  loadLocalApps()
})
</script>

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

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

.upload-card {
  border: 2px dashed #d1d5db;
  transition: all 0.2s ease;
}

.upload-card:hover {
  border-color: #3b82f6;
}

.upload-content {
  padding: 40px 20px;
  text-align: center;
}

.app-name-input {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
}

.upload-actions {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
}

.progress-content {
  padding: 20px 0;
}

.progress-text {
  display: block;
  text-align: center;
  margin-top: 12px;
  font-size: 14px;
}

.local-apps-section {
  margin-top: 32px;
}

.local-apps-card {
  border: 1px solid #e5e7eb;
}

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

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