<script setup lang="ts">
import { Box, Boxes, Loader2 } from 'lucide-vue-next'
import { onMounted, ref } from 'vue'

import api from '@/services/api'

interface App {
  id: number
  name: string
  description: string
  status: string
  card_types_count: number
  created_at: string
}

const loading = ref(true)
const apps = ref<App[]>([])

onMounted(async () => {
  try {
    const data = await api.get<App[]>('/agent/apps')
    apps.value = data || []
  }
  catch (error) {
    console.error('获取应用列表失败:', error)
  }
  finally {
    loading.value = false
  }
})

function formatDate(dateStr: string) {
  return new Date(dateStr).toLocaleDateString('zh-CN')
}
</script>

<template>
  <div class="space-y-6">
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-2xl font-bold">
          应用管理
        </h1>
        <p class="text-muted-foreground">
          管理您授权的应用
        </p>
      </div>
    </div>

    <UiCard>
      <UiCardContent class="p-0">
        <div v-if="loading" class="flex items-center justify-center py-12">
          <Loader2 class="size-8 animate-spin text-muted-foreground" />
        </div>

        <div v-else-if="apps.length === 0" class="text-center py-12 text-muted-foreground">
          <Boxes class="size-16 mx-auto mb-4 opacity-30" />
          <p>暂无授权应用</p>
        </div>

        <div v-else class="divide-y">
          <div
            v-for="app in apps"
            :key="app.id"
            class="flex items-center justify-between p-4 hover:bg-muted/50 transition-colors"
          >
            <div class="flex items-center gap-4">
              <div class="size-12 rounded-xl bg-primary/10 flex items-center justify-center">
                <Box class="size-6 text-primary" />
              </div>
              <div>
                <h3 class="font-medium">
                  {{ app.name }}
                </h3>
                <p class="text-sm text-muted-foreground">
                  {{ app.description || '暂无描述' }}
                </p>
              </div>
            </div>
            <div class="flex items-center gap-4">
              <div class="text-right">
                <p class="text-sm font-medium">
                  {{ app.card_types_count }} 种卡类
                </p>
                <p class="text-xs text-muted-foreground">
                  {{ formatDate(app.created_at) }}
                </p>
              </div>
              <UiButton variant="outline" size="sm" as-child>
                <router-link :to="`/agent/apps/${app.id}`">
                  查看
                </router-link>
              </UiButton>
            </div>
          </div>
        </div>
      </UiCardContent>
    </UiCard>
  </div>
</template>
