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

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

import ConfirmDialog from '@/components/confirm-dialog.vue'
import SingleFilter from '@/components/data-table/single-filter.vue'
import { BasicPage } from '@/components/global-layout'
import DataTable from '@/pages/admin/agent-apps/components/data-table.vue'
import api from '@/services/api'

const router = useRouter()

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

const statusFilter = ref<string>('')

const deleteDialogOpen = ref(false)
const deleteTarget = ref<AgentApp | null>(null)
const batchDeleteDialogOpen = ref(false)
const batchDeleteIds = ref<(string | number)[]>([])

const filteredApps = computed(() => {
  let result = agentApps.value

  if (statusFilter.value) {
    result = result.filter(app => app.status === statusFilter.value)
  }

  return result
})

const activeCount = computed(() => filteredApps.value.filter(app => app.status === 'active').length)
const inactiveCount = computed(() => filteredApps.value.filter(app => app.status === 'inactive').length)
const totalBalance = computed(() => filteredApps.value.reduce((sum, app) => sum + (app.balance || 0), 0))

const statusOptions = computed(() => [
  { label: '已启用', value: 'active' },
  { label: '已禁用', value: 'inactive' },
])

async function fetchData() {
  loading.value = true
  try {
    const data = await api.get<{ agent_apps: AgentApp[] }>('/dev/agent-apps')
    agentApps.value = data?.agent_apps || []
  }
  catch (error) {
    console.error('获取数据失败:', error)
    toast.error('获取授权列表失败')
  }
  finally {
    loading.value = false
  }
}

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

function handleView(item: AgentApp) {
  router.push(`/admin/agent-apps/${item.id}/view`)
}

function handleEdit(item: AgentApp) {
  router.push(`/admin/agent-apps/${item.id}/edit`)
}

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

async function handleDelete() {
  if (!deleteTarget.value)
    return

  try {
    await api.delete(`/dev/agent-apps/${deleteTarget.value.id}`)
    toast.success('移除授权成功')
    fetchData()
  }
  catch (error: any) {
    console.error('移除失败:', error)
    toast.error(error.message || '移除失败')
  }
  finally {
    deleteTarget.value = null
  }
}

function confirmBatchDelete(ids: (string | number)[]) {
  batchDeleteIds.value = ids
  batchDeleteDialogOpen.value = true
}

async function handleBatchDelete() {
  try {
    for (const id of batchDeleteIds.value) {
      await api.delete(`/dev/agent-apps/${id}`)
    }
    toast.success('批量移除成功')
    fetchData()
  }
  catch (error: any) {
    console.error('批量移除失败:', error)
    toast.error(error.message || '批量移除失败')
  }
  finally {
    batchDeleteIds.value = []
  }
}

onMounted(() => {
  fetchData()
})

onActivated(() => {
  fetchData()
})
</script>

<template>
  <BasicPage
    title="授权管理"
    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-4">
        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              授权总数
            </UiCardTitle>
            <Share2 class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ filteredApps.length }}
            </div>
          </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">
              {{ activeCount }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              已禁用
            </UiCardTitle>
            <XCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ inactiveCount }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              代理余额总计
            </UiCardTitle>
            <Key class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              ¥{{ totalBalance.toFixed(2) }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            ref="tableRef"
            :loading
            :data="filteredApps"
            :on-view="handleView"
            :on-edit="handleEdit"
            :on-delete="confirmDelete"
            @refresh="fetchData"
            @batch-delete="confirmBatchDelete"
          >
            <template #filters>
              <SingleFilter
                v-model="statusFilter"
                title="状态"
                :options="statusOptions"
              />
            </template>
          </DataTable>
        </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>

    <ConfirmDialog
      v-model:open="batchDeleteDialogOpen"
      destructive
      confirm-button-text="确定移除"
      cancel-button-text="取消"
      @confirm="handleBatchDelete"
    >
      <template #title>
        批量移除授权
      </template>
      <template #description>
        确定要移除选中的 {{ batchDeleteIds.length }} 项授权吗？
      </template>
    </ConfirmDialog>
  </BasicPage>
</template>
