<script setup lang="ts">
import { ArrowLeft, CheckCircle, Key, Loader2, Pencil, XCircle } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import type { AgentApp } from '@/pages/admin/agent-apps/data/schema'

import { BasicPage } from '@/components/global-layout'
import api from '@/services/api'

const route = useRoute()
const router = useRouter()

const loading = ref(true)
const agentApp = ref<AgentApp | null>(null)

const agentAppId = computed(() => route.params.id as string)

function getBillingTypeText(type: string) {
  const map: Record<string, string> = {
    subscription: '订阅',
    time: '计时',
    point: '点卡',
  }
  return map[type] || type
}

async function fetchAgentApp() {
  loading.value = true
  try {
    const data = await api.get<{ agent_app: AgentApp }>(`/dev/agent-apps/${agentAppId.value}`)
    if (data?.agent_app) {
      agentApp.value = data.agent_app
    }
    else {
      toast.error('获取授权信息失败')
      router.push('/admin/agent-apps')
    }
  }
  catch (error) {
    console.error('获取授权信息失败:', error)
    toast.error('获取授权信息失败')
    router.push('/admin/agent-apps')
  }
  finally {
    loading.value = false
  }
}

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

function goToEdit() {
  router.push(`/admin/agent-apps/${agentAppId.value}/edit`)
}

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

<template>
  <BasicPage
    title="查看授权"
    description="查看授权详情信息"
    :breadcrumbs="[
      { title: '授权管理', href: '/admin/agent-apps' },
      { title: '查看授权' },
    ]"
    sticky
  >
    <template #actions>
      <UiButton variant="outline" @click="goBack">
        <ArrowLeft class="mr-2 h-4 w-4" />
        返回
      </UiButton>
      <UiButton @click="goToEdit">
        <Pencil class="mr-2 h-4 w-4" />
        编辑授权
      </UiButton>
    </template>

    <div v-if="loading" class="flex items-center justify-center py-12">
      <Loader2 class="h-8 w-8 animate-spin text-muted-foreground" />
    </div>

    <div v-else-if="agentApp" class="space-y-6">
      <div class="grid gap-6 lg:grid-cols-3">
        <div class="lg:col-span-2 space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle>基本信息</UiCardTitle>
              <UiCardDescription>授权的基本信息</UiCardDescription>
            </UiCardHeader>
            <UiCardContent>
              <div class="grid grid-cols-2 gap-6">
                <div class="space-y-1">
                  <span class="text-sm text-muted-foreground">代理</span>
                  <p class="font-medium">{{ agentApp.agent_name }}</p>
                  <p v-if="agentApp.agent_email" class="text-xs text-muted-foreground">
                    {{ agentApp.agent_email }}
                  </p>
                </div>
                <div class="space-y-1">
                  <span class="text-sm text-muted-foreground">应用</span>
                  <p class="font-medium">{{ agentApp.app_name }}</p>
                </div>
                <div class="space-y-1">
                  <span class="text-sm text-muted-foreground">状态</span>
                  <div>
                    <UiBadge :variant="agentApp.status === 'active' ? 'default' : 'secondary'">
                      <CheckCircle v-if="agentApp.status === 'active'" class="mr-1 h-3 w-3" />
                      <XCircle v-else class="mr-1 h-3 w-3" />
                      {{ agentApp.status === 'active' ? '已启用' : '已禁用' }}
                    </UiBadge>
                  </div>
                </div>
                <div class="space-y-1">
                  <span class="text-sm text-muted-foreground">折扣</span>
                  <p class="font-medium">{{ (agentApp.discount * 10).toFixed(1) }}折</p>
                </div>
                <div class="space-y-1">
                  <span class="text-sm text-muted-foreground">余额</span>
                  <p class="font-medium text-primary">¥{{ (agentApp.balance || 0).toFixed(2) }}</p>
                </div>
                <div class="space-y-1">
                  <span class="text-sm text-muted-foreground">授权时间</span>
                  <p class="font-medium">{{ agentApp.created_at }}</p>
                </div>
              </div>
            </UiCardContent>
          </UiCard>

          <UiCard>
            <UiCardHeader>
              <UiCardTitle class="flex items-center gap-2">
                <Key class="size-5" />
                卡密权限
              </UiCardTitle>
              <UiCardDescription>代理可生成的卡密类型及价格</UiCardDescription>
            </UiCardHeader>
            <UiCardContent>
              <div v-if="agentApp.card_types && agentApp.card_types.length > 0">
                <UiTable>
                  <UiTableHeader>
                    <UiTableRow>
                      <UiTableHead>卡类名称</UiTableHead>
                      <UiTableHead>计费类型</UiTableHead>
                      <UiTableHead>原价</UiTableHead>
                      <UiTableHead>授权价格</UiTableHead>
                      <UiTableHead>状态</UiTableHead>
                    </UiTableRow>
                  </UiTableHeader>
                  <UiTableBody>
                    <UiTableRow v-for="ct in agentApp.card_types" :key="ct.card_type_id || ct.id">
                      <UiTableCell class="font-medium">
                        {{ ct.name }}
                      </UiTableCell>
                      <UiTableCell>
                        <UiBadge variant="outline">
                          {{ getBillingTypeText(ct.billing_type || '') }}
                        </UiBadge>
                      </UiTableCell>
                      <UiTableCell>
                        ¥{{ ct.origin_price || 0 }}
                      </UiTableCell>
                      <UiTableCell>
                        ¥{{ ct.price || 0 }}
                      </UiTableCell>
                      <UiTableCell>
                        <UiBadge :variant="ct.can_generate ? 'default' : 'secondary'">
                          {{ ct.can_generate ? '已授权' : '未授权' }}
                        </UiBadge>
                      </UiTableCell>
                    </UiTableRow>
                  </UiTableBody>
                </UiTable>
              </div>
              <div v-else class="text-center py-8 text-muted-foreground">
                暂无卡密权限
              </div>
            </UiCardContent>
          </UiCard>
        </div>

        <div class="space-y-6">
          <UiCard>
            <UiCardHeader>
              <UiCardTitle>统计信息</UiCardTitle>
            </UiCardHeader>
            <UiCardContent class="space-y-4">
              <div class="space-y-3">
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">卡类总数</span>
                  <span class="font-medium">{{ agentApp.card_types?.length || 0 }}</span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">已授权</span>
                  <span class="font-medium text-green-600">
                    {{ agentApp.card_types?.filter(ct => ct.can_generate).length || 0 }}
                  </span>
                </div>
                <div class="flex justify-between text-sm">
                  <span class="text-muted-foreground">未授权</span>
                  <span class="font-medium text-muted-foreground">
                    {{ agentApp.card_types?.filter(ct => !ct.can_generate).length || 0 }}
                  </span>
                </div>
              </div>
            </UiCardContent>
          </UiCard>

          <UiCard>
            <UiCardContent class="pt-6">
              <div class="flex flex-col gap-3">
                <UiButton class="w-full" @click="goToEdit">
                  <Pencil class="mr-2 h-4 w-4" />
                  编辑授权
                </UiButton>
                <UiButton variant="outline" class="w-full" @click="goBack">
                  返回列表
                </UiButton>
              </div>
            </UiCardContent>
          </UiCard>
        </div>
      </div>
    </div>
  </BasicPage>
</template>
