<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { NCard, NButton, NSkeleton, NSpace, NTag, NModal, NForm, NFormItem, NInput, NSelect, NEmpty, NAlert, NPopconfirm, NPagination, NIcon, type FormRules } from 'naive-ui'
import { KeyOutline, AddOutline } from '@vicons/ionicons5'
import { api } from '../../api/client'
import { useToast } from '../../composables/useToast'

const keys = ref<any[]>([])
const usage = ref<any[]>([])
const webhooks = ref<any[]>([])
const toast = useToast()
const loading = ref(true)
const keyCreating = ref(false)
const webhookCreating = ref(false)
const showKey = ref(false)
const newKey = ref({ name: '', scopes: ['read'] })
const keyFormRef = ref()
const keyRules: FormRules = {
  name: { required: true, message: '请输入密钥名称', trigger: 'blur' },
}
const generatedKey = ref('')
const showWebhook = ref(false)
const newWebhook = ref({ url: '', events: ['literature.new'] })
const webhookFormRef = ref()
const webhookRules: FormRules = {
  url: [
    { required: true, message: '请输入 Webhook URL', trigger: 'blur' },
    { type: 'url', message: 'URL 格式不正确', trigger: 'blur' },
  ],
}
const usagePage = ref(1)
const usagePageSize = ref(20)
const usageTotal = ref(0)

onMounted(loadData)
async function loadData() {
  loading.value = true
  try {
    const [kRes, uRes, wRes] = await Promise.all([
      api.get('/api-management/keys'), api.get('/api-management/usage', { params: { page: usagePage.value, page_size: usagePageSize.value } }), api.get('/api-management/webhooks'),
    ])
    keys.value = kRes.data.items || []; usage.value = uRes.data.items || []; webhooks.value = wRes.data.items || []
    usageTotal.value = uRes.data.total || 0
  } catch (e) { toast.apiError(e, '加载API管理数据失败') }
  finally { loading.value = false }
}
async function createKey() {
  try { await keyFormRef.value?.validate() } catch { return }
  keyCreating.value = true
  try { const { data } = await api.post('/api-management/keys', newKey.value); generatedKey.value = data.api_key; loadData() } catch (e) { toast.apiError(e, "生成API密钥失败") } finally { keyCreating.value = false }
}
async function revokeKey(id: string) {
  try { await api.delete(`/api-management/keys/${id}`); loadData() } catch (e) { toast.apiError(e, "吊销密钥失败") }
}
async function createWebhook() {
  try { await webhookFormRef.value?.validate() } catch { return }
  webhookCreating.value = true
  try { await api.post('/api-management/webhooks', newWebhook.value); showWebhook.value=false; loadData() } catch (e) { toast.apiError(e, "创建Webhook失败") } finally { webhookCreating.value = false }
}
async function deleteWebhook(id: string) {
  try { await api.delete(`/api-management/webhooks/${id}`); loadData() } catch (e) { toast.apiError(e, "删除Webhook失败") }
}
</script>

<template>
  <div style="max-width:1400px;margin:0 auto;padding:24px">
    <div style="display:flex;justify-content:space-between;margin-bottom:16px">
      <h2>🔌 API 管理</h2>
      <n-space>
        <NButton @click="showKey=true" class="sky-btn"><template #icon><NIcon size="14"><AddOutline /></NIcon></template>API Key</NButton>
        <NButton @click="showWebhook=true" class="sky-btn"><template #icon><NIcon size="14"><AddOutline /></NIcon></template>Webhook</NButton>
      </n-space>
    </div>
    <NAlert type="info" style="margin-bottom:16px" title="API 密钥用于第三方集成 · 文档见 /docs · Free: 100次/天, Pro: 1000次/天, Team: 5000次/天" />

    <NSkeleton v-if="loading" text :repeat="6" />
    <template v-if="!loading">
    <NCard title="🔑 API 密钥" size="small" style="margin-bottom:24px">
      <NEmpty v-if="!keys.length" description="暂无密钥" />
      <div v-for="k in keys" :key="k.id" style="display:flex;align-items:center;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--border-color);font-size:13px">
        <span><strong>{{ k.name }}</strong> ({{ k.prefix }}...)</span>
        <n-space><NTag size="tiny" v-for="s in k.scopes" :key="s">{{ s }}</NTag><NPopconfirm @positive-click="revokeKey(k.id)"><template #trigger><NButton size="tiny" type="error" text>吊销</NButton></template>确认吊销此密钥？</NPopconfirm></n-space>
      </div>
    </NCard>

    <NCard title="📡 调用日志" size="small" style="margin-bottom:24px">
      <NEmpty v-if="!usage.length" description="暂无调用记录" />
      <div v-for="u in usage" :key="u.time" style="display:flex;gap:12px;padding:4px 0;font-size:12px;color:var(--text-secondary);border-bottom:1px solid var(--border-color)">
        <span>{{ u.method }}</span><span>{{ u.endpoint }}</span><span>{{ u.status }}</span><span>{{ u.ms }}ms</span><span>{{ u.time?.slice(0,19) }}</span>
      </div>
      <div v-if="usageTotal > usagePageSize" style="display:flex;justify-content:center;margin-top:12px">
        <NPagination :page="usagePage" :page-size="usagePageSize" :item-count="usageTotal" @update:page="p => { usagePage=p; loadData() }" />
      </div>
    </NCard>

    <NCard title="🔗 Webhooks" size="small">
      <NEmpty v-if="!webhooks.length" description="暂无 Webhook" />
      <div v-for="w in webhooks" :key="w.id" style="display:flex;align-items:center;justify-content:space-between;padding:6px 0;font-size:13px">
        <span>{{ w.url }}</span>
        <n-space><NTag size="tiny" v-for="e in w.events" :key="e">{{ e }}</NTag><NPopconfirm @positive-click="deleteWebhook(w.id)"><template #trigger><NButton size="tiny" text type="error">删除</NButton></template>确认删除此 Webhook？</NPopconfirm></n-space>
      </div>
    </NCard>
    </template>

    <NModal v-model:show="showKey" title="生成 API Key" preset="card" style="width:450px">
      <NForm ref="keyFormRef" :model="newKey" :rules="keyRules" label-placement="left" label-width="60">
        <NFormItem path="name" label="名称"><NInput v-model:value="newKey.name" placeholder="如：Zotero集成" /></NFormItem>
        <NFormItem label="权限"><NSelect v-model:value="newKey.scopes" multiple :options="[{label:'读取',value:'read'},{label:'写入',value:'write'}]" /></NFormItem>
        <NButton class="sky-btn" type="primary" block :loading="keyCreating" @click="createKey"><template #icon><NIcon size="14"><KeyOutline /></NIcon></template>生成</NButton>
        <div v-if="generatedKey" style="background:var(--bg-hover);padding:12px;border-radius:6px;margin-top:12px;word-break:break-all;font-size:13px;font-family:monospace">
          {{ generatedKey }}
          <div style="color:#d03050;font-size:11px;margin-top:4px">⚠️ 此密钥仅显示一次，请立即保存</div>
        </div>
      </NForm>
    </NModal>

    <NModal v-model:show="showWebhook" title="添加 Webhook" preset="card" style="width:450px">
      <NForm ref="webhookFormRef" :model="newWebhook" :rules="webhookRules" label-placement="left" label-width="60">
        <NFormItem path="url" label="URL"><NInput v-model:value="newWebhook.url" placeholder="https://your-server.com/hook" /></NFormItem>
        <NFormItem label="事件"><NSelect v-model:value="newWebhook.events" multiple :options="[{label:'新文献',value:'literature.new'},{label:'新Feed',value:'feed.new'}]" /></NFormItem>
        <NButton class="sky-btn" type="primary" block :loading="webhookCreating" @click="createWebhook"><template #icon><NIcon size="14"><AddOutline /></NIcon></template>添加</NButton>
      </NForm>
    </NModal>
  </div>
</template>
