<script setup lang="ts">
import { CheckCircle, KeyRound, Network, Plus } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import type { AgentApp } from './data/schema'

import ConfirmDialog from '@/components/confirm-dialog.vue'
import { BasicPage } from '@/components/global-layout'
import DataTable from './components/data-table.vue'
import api from '@/services/api'

const { t } = useI18n()
const router = useRouter()

const loading = ref(true)
const agentApps = ref<AgentApp[]>([])
const tableRef = ref()

const deleteDialogOpen = ref(false)
const deleteTarget = ref<AgentApp | null>(null)

const totalAuthApps = computed(() => agentApps.value.length)
const activeAuthApps = computed(() => agentApps.value.filter(app => app.status === 'active').length)
const totalCardTypes = computed(() => {
  return agentApps.value.reduce((sum, app) => {
    return sum + (app.card_types?.filter(c => c.can_generate).length || 0)
  }, 0)
})

async function fetchAgentApps() {
  loading.value = true
  try {
    const data = await api.get<{ agent_apps?: AgentApp[] }>('/dev/agent-apps')
    agentApps.value = Array.isArray(data) ? data : (data?.agent_apps || [])
  }
  catch {
    agentApps.value = []
  }
  finally {
    loading.value = false
  }
}

function goToCreate() {
  router.push('/admin/agent-apps/create')
}

function goToEdit(app: AgentApp) {
  router.push(`/admin/agent-apps/${app.id}`)
}

function confirmDelete(app: AgentApp) {
  deleteTarget.value = app
  deleteDialogOpen.value = true
}

async function handleDelete() {
  if (!deleteTarget.value) return
  
  try {
    await api.delete(`/dev/agent-apps/${deleteTarget.value.id}`)
    toast.success('删除授权成功')
    fetchAgentApps()
  }
  catch (error: any) {
    toast.error(error.message || '删除失败')
  }
  finally {
    deleteTarget.value = null
  }
}

async function handleToggleStatus(app: AgentApp) {
  try {
    const newStatus = app.status === 'active' ? 'inactive' : 'active'
    await api.put(`/dev/agent-apps/${app.id}/status`, { status: newStatus })
    toast.success('状态更新成功')
    fetchAgentApps()
  }
  catch (error: any) {
    toast.error(error.message || '更新失败')
  }
}

onMounted(() => {
  fetchAgentApps()
})
</script>

<template>
  <BasicPage
    :title="t('nav.agentApps')"
    description="管理代理的应用授权和卡类权限"
    sticky
  >
    <template #actions>
      <UiButton @click="goToCreate">
        <Plus class="mr-2 h-4 w-4" />
        添加授权
      </UiButton>
    </template>

    <div class="space-y-6">
      <div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              授权应用总数
            </UiCardTitle>
            <KeyRound class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ totalAuthApps }}
            </div>
            <p class="text-xs text-muted-foreground mt-1">
              已授权的应用数量
            </p>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              活跃授权
            </UiCardTitle>
            <CheckCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ activeAuthApps }}
            </div>
            <p class="text-xs text-muted-foreground mt-1">
              状态为启用的授权
            </p>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              授权卡类
            </UiCardTitle>
            <Network class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ totalCardTypes }}
            </div>
            <p class="text-xs text-muted-foreground mt-1">
              已授权的卡类总数
            </p>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            ref="tableRef"
            :loading
            :data="agentApps"
            :on-edit="goToEdit"
            :on-delete="confirmDelete"
            :on-toggle-status="handleToggleStatus"
            @refresh="fetchAgentApps"
          />
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="deleteDialogOpen"
      destructive
      confirm-button-text="删除"
      cancel-button-text="取消"
      @confirm="handleDelete"
    >
      <template #title>
        删除授权
      </template>
      <template #description>
        确定要删除代理「{{ deleteTarget?.agent_name }}」对应用「{{ deleteTarget?.app_name }}」的授权吗？此操作不可撤销。
      </template>
    </ConfirmDialog>
  </BasicPage>
</template>
