<script setup lang="ts">
import { useAdminApiKeyStore } from '@/stores/admin-api-key'
import { SearchOutlined, ReloadOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import type { ApiKeyRecord } from '@/types/api'

const store = useAdminApiKeyStore()

// a-select 不接受 boolean，用 number (1/0) 做本地中间态
const enabledFilter = computed<number | undefined>({
  get: () => (store.filters.enabled === undefined ? undefined : store.filters.enabled ? 1 : 0),
  set: (val) => {
    store.filters.enabled = val === undefined ? undefined : val === 1
  },
})

const columns = [
  { title: 'ID', dataIndex: 'id', width: 70 },
  { title: '用户', key: 'user', width: 160 },
  { title: '名称', dataIndex: 'name', width: 150 },
  { title: '前缀', key: 'prefix', width: 120 },
  { title: '创建时间', dataIndex: 'created_at', width: 170 },
  { title: '过期时间', key: 'expires_at', width: 170 },
  { title: '最后使用', key: 'last_used_at', width: 170 },
  { title: '状态', key: 'enabled', width: 100 },
  { title: '操作', key: 'action', width: 80 },
]

onMounted(() => store.fetchAllKeys())

function handleSearch() {
  store.pagination.page = 1
  store.fetchAllKeys()
}

function handleReset() {
  store.resetFilters()
  store.fetchAllKeys()
}

function handlePageChange(page: number, pageSize: number) {
  store.pagination.page = page
  store.pagination.per_page = pageSize
  store.fetchAllKeys()
}

function formatTime(t: string | null, fallback: string) {
  return t ? t.replace('T', ' ').substring(0, 19) : fallback
}

function handleToggle(id: number, checked: boolean | string) {
  store.toggleKey(id, Boolean(checked))
}

function handleDelete(id: number) {
  store.deleteKey(id)
}
</script>

<template>
  <div>
    <h2 class="text-xl font-semibold mb-4">API Key 管理</h2>

    <!-- 筛选区 -->
    <div class="flex gap-3 mb-4 flex-wrap">
      <a-input
        v-model:value="store.filters.username"
        placeholder="用户名"
        style="width: 150px"
        allow-clear
        @press-enter="handleSearch"
      />
      <a-input
        v-model:value="store.filters.email"
        placeholder="邮箱"
        style="width: 180px"
        allow-clear
        @press-enter="handleSearch"
      />
      <a-select
        v-model:value="enabledFilter"
        placeholder="启用状态"
        style="width: 120px"
        allow-clear
      >
        <a-select-option :value="1">启用</a-select-option>
        <a-select-option :value="0">禁用</a-select-option>
      </a-select>
      <a-button type="primary" @click="handleSearch">
        <template #icon><SearchOutlined /></template>
        搜索
      </a-button>
      <a-button @click="handleReset">
        <template #icon><ReloadOutlined /></template>
        重置
      </a-button>
    </div>

    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="store.keys"
      :loading="store.loading"
      :pagination="false"
      :scroll="{ x: 1200 }"
      row-key="id"
      size="middle"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'user'">
          <div>
            <span>{{ (record as ApiKeyRecord).user?.username ?? record.user_id }}</span>
            <a-tooltip
              v-if="(record as ApiKeyRecord).user?.api_key_enabled === false"
              title="该用户的 API Key 功能已关闭，所有 Key 均无法认证"
            >
              <a-tag color="red" class="ml-1">已停用</a-tag>
            </a-tooltip>
          </div>
          <div v-if="(record as ApiKeyRecord).user?.email" class="text-xs text-gray-400">
            {{ (record as ApiKeyRecord).user!.email }}
          </div>
        </template>

        <template v-else-if="column.key === 'prefix'">
          {{ record.key_prefix }}****
        </template>

        <template v-else-if="column.key === 'expires_at'">
          {{ formatTime(record.expires_at as string | null, '永不过期') }}
        </template>

        <template v-else-if="column.key === 'last_used_at'">
          {{ formatTime(record.last_used_at as string | null, '从未使用') }}
        </template>

        <template v-else-if="column.key === 'enabled'">
          <a-switch
            :checked="record.enabled as boolean"
            @change="(checked) => handleToggle(record.id as number, checked as boolean | string)"
          />
        </template>

        <template v-else-if="column.key === 'action'">
          <a-popconfirm
            title="确认删除该 API Key？"
            ok-text="删除"
            cancel-text="取消"
            @confirm="handleDelete(record.id as number)"
          >
            <a-button type="text" danger size="small">
              <template #icon><DeleteOutlined /></template>
            </a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <!-- 分页 -->
    <div class="flex justify-end mt-4">
      <a-pagination
        :current="store.pagination.page"
        :page-size="store.pagination.per_page"
        :total="store.pagination.total"
        show-size-changer
        show-quick-jumper
        :page-size-options="['15', '30', '50']"
        @change="handlePageChange"
        @show-size-change="handlePageChange"
      />
    </div>
  </div>
</template>
