<!-- Package详情页工具栏组件 -->
<template>
  <div class="package-toolbar">
    <n-space>
      <!-- 卸载按钮 -->
      <n-button 
        type="error" 
        @click="showUninstallDialog"
        :disabled="context.loading"
        class="uninstall-btn"
      >
        <template #icon>
          <n-icon><Icon icon="tabler:trash" /></n-icon>
        </template>
        {{ context.t('Uninstall Package') }}
      </n-button>
      
      <!-- 查看软件包资源按钮 -->
      <n-button 
        type="default" 
        @click="showResources"
        :disabled="context.loading"
      >
        <template #icon>
          <n-icon><Icon icon="tabler:info-circle" /></n-icon>
        </template>
        {{ context.t('Package Resources') }}
      </n-button>
    </n-space>

    <!-- 软件包资源模态框 -->
    <n-modal v-model:show="showResourcesModal">
      <n-card style="width: 500px" :title="context.t('Package Resources')">
        <div class="package-resources">
          <h4>{{ context.t('Package') }}: {{ resourcesData.package_name }}</h4>
          <div class="summary-stats">
            <p><strong>{{ context.t('Modules') }}:</strong> {{ resourcesData.summary?.modules_count || 0 }}</p>
            <p><strong>{{ context.t('PageTypes') }}:</strong> {{ resourcesData.summary?.pagetypes_count || 0 }}</p>
            <p><strong>{{ context.t('Releases') }}:</strong> {{ resourcesData.summary?.releases_count || 0 }}</p>
          </div>
          
          <div v-if="resourcesData.modules && resourcesData.modules.length > 0" class="modules-section">
            <h5>{{ context.t('Modules') }}:</h5>
            <div class="item-list">{{ resourcesData.modules.join(', ') }}</div>
          </div>
          
          <div v-if="resourcesData.pagetypes && resourcesData.pagetypes.length > 0" class="pagetypes-section">
            <h5>{{ context.t('PageTypes') }}:</h5>
            <div class="item-list">{{ resourcesData.pagetypes.join(', ') }}</div>
          </div>

          <div v-if="resourcesData.releases && resourcesData.releases.length > 0" class="releases-section">
            <h5>{{ context.t('Releases') }}:</h5>
            <div class="item-list">{{ resourcesData.releases.join(', ') }}</div>
          </div>
        </div>
        <template #footer>
          <n-space justify="end">
            <n-button @click="showResourcesModal = false">{{ context.t('OK') }}</n-button>
          </n-space>
        </template>
      </n-card>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { NButton, NSpace, NIcon, NModal, NCard, useDialog, useMessage } from 'naive-ui'
import { Icon } from '@iconify/vue'
import axios from 'axios'

const props = defineProps<{
  context: {
    entity: string
    id: string
    record: any
    canEdit: boolean
    loading: boolean
    save: () => Promise<void>
    router: any
    t: (key: string) => string
  }
}>()

const dialog = useDialog()
const message = useMessage()
const uninstalling = ref(false)
const showResourcesModal = ref(false)
const resourcesData = ref<any>({})

// 显示卸载确认对话框
const showUninstallDialog = () => {
  const packageName = props.context.record.name
  
  dialog.warning({
    title: props.context.t('Uninstall Package'),
    content: props.context.t('Are you sure you want to uninstall this package? This will remove all associated modules and pagetypes. This action cannot be undone.'),
    positiveText: props.context.t('Uninstall'),
    negativeText: props.context.t('Cancel'),
    onPositiveClick: async () => {
      await uninstallPackage(packageName)
    }
  })
}

// 卸载软件包
const uninstallPackage = async (packageName: string) => {
  try {
    uninstalling.value = true
    
    // 调用本地API，它会先卸载数据库，再删除本地模块
    const response = await axios.post(`/jingrow/uninstall-extension/${packageName}`, {})
    
    if (response.data.success) {
      message.success(props.context.t("Package '{0}' uninstalled successfully").replace('{0}', packageName))
      
      // 卸载成功后跳转到Package列表页
      props.context.router.push('/app/package')
    } else {
      message.error(props.context.t("Failed to uninstall package"))
    }
  } catch (error: any) {
    console.error('Uninstall package error:', error)
    message.error(error.response?.data?.message || props.context.t('Failed to uninstall package'))
  } finally {
    uninstalling.value = false
  }
}

// 显示软件包资源
const showResources = async () => {
  try {
    const packageName = props.context.record.name
    
    const response = await axios.post('/jingrow/get-package-dependencies', {
      package_name: packageName
    })
    
    if (response.data.message.status === 'success') {
      resourcesData.value = response.data.message
      showResourcesModal.value = true
    } else {
      message.error(response.data.message.message)
    }
  } catch (error: any) {
    console.error('Get package resources error:', error)
    message.error(error.response?.data?.message || props.context.t('Failed to get package resources'))
  }
}
</script>

<style scoped>
.package-toolbar {
  display: flex;
  align-items: center;
}

.uninstall-btn {
  background-color: #dc2626;
  border-color: #dc2626;
}

.uninstall-btn:hover {
  background-color: #b91c1c;
  border-color: #b91c1c;
}

.package-resources {
  max-height: 400px;
  overflow-y: auto;
  padding: 12px 0;
}

.package-resources h4 {
  margin: 0 0 16px 0;
  color: #1f2937;
  font-size: 16px;
  font-weight: 600;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 8px;
}

.summary-stats {
  background: #f8fafc;
  padding: 12px 16px;
  border-radius: 6px;
  margin-bottom: 16px;
  border: 1px solid #e2e8f0;
}

.summary-stats p {
  margin: 6px 0;
  color: #475569;
  font-size: 13px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-stats strong {
  color: #1e293b;
  font-weight: 500;
}

.modules-section,
.pagetypes-section,
.releases-section {
  margin-bottom: 16px;
}

.package-resources h5 {
  margin: 0 0 8px 0;
  color: #475569;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.package-resources h5::before {
  content: '';
  width: 3px;
  height: 14px;
  background: #6366f1;
  margin-right: 6px;
  border-radius: 2px;
}

.item-list {
  color: #64748b;
  font-size: 13px;
  line-height: 1.4;
  padding: 8px 12px;
  border-radius: 4px;
  background: #f1f5f9;
  border-left: 3px solid #cbd5e1;
  word-break: break-all;
}
</style>
