<template>
  <div class="whitelist-manager">
    <a-tabs v-model:activeKey="activeTab">
      <!-- User whitelist -->
      <a-tab-pane key="user" tab="我的白名单">
        <div class="whitelist-manager__section">
          <div class="whitelist-manager__add-form">
            <a-input
              v-model:value="newUserPattern"
              placeholder="输入命令模式，如: git, npm, ls"
              @press-enter="addUserEntry"
              :disabled="userLoading"
            />
            <a-button type="primary" @click="addUserEntry" :loading="userLoading">
              添加
            </a-button>
          </div>
          <a-table
            :data-source="userWhitelist"
            :columns="whitelistColumns"
            :loading="userLoading"
            :pagination="{ pageSize: 10 }"
            row-key="id"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <a-button
                  type="link"
                  danger
                  size="small"
                  @click="deleteUserEntry(record.id)"
                >
                  删除
                </a-button>
              </template>
            </template>
          </a-table>
        </div>
      </a-tab-pane>

      <!-- Global whitelist (admin only) -->
      <a-tab-pane
        v-if="authStore.isAdmin()"
        key="global"
        tab="全局白名单"
      >
        <div class="whitelist-manager__section">
          <a-alert
            message="全局白名单对所有用户生效，由管理员维护"
            type="info"
            show-icon
            style="margin-bottom: 12px"
          />
          <div class="whitelist-manager__add-form">
            <a-input
              v-model:value="newGlobalPattern"
              placeholder="输入命令模式，如: docker, kubectl"
              @press-enter="addGlobalEntry"
              :disabled="globalLoading"
            />
            <a-button type="primary" @click="addGlobalEntry" :loading="globalLoading">
              添加
            </a-button>
          </div>
          <a-table
            :data-source="globalWhitelist"
            :columns="whitelistColumns"
            :loading="globalLoading"
            :pagination="{ pageSize: 10 }"
            row-key="id"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <a-button
                  type="link"
                  danger
                  size="small"
                  @click="deleteGlobalEntry(record.id)"
                >
                  删除
                </a-button>
              </template>
            </template>
          </a-table>
        </div>
      </a-tab-pane>

      <!-- Blocklist (admin only) -->
      <a-tab-pane
        v-if="authStore.isAdmin()"
        key="blocklist"
        tab="黑名单"
      >
        <div class="whitelist-manager__section">
          <a-alert
            message="黑名单中的命令将被完全禁止执行，优先级最高"
            type="warning"
            show-icon
            style="margin-bottom: 12px"
          />
          <div class="whitelist-manager__add-form">
            <a-input
              v-model:value="newBlockPattern"
              placeholder="输入要禁止的命令模式"
              style="flex: 2"
              @press-enter="addBlockEntry"
              :disabled="blockLoading"
            />
            <a-input
              v-model:value="newBlockReason"
              placeholder="禁止原因"
              style="flex: 3"
              @press-enter="addBlockEntry"
              :disabled="blockLoading"
            />
            <a-button type="primary" danger @click="addBlockEntry" :loading="blockLoading">
              添加
            </a-button>
          </div>
          <a-table
            :data-source="blocklist"
            :columns="blocklistColumns"
            :loading="blockLoading"
            :pagination="{ pageSize: 10 }"
            row-key="id"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <a-button
                  type="link"
                  danger
                  size="small"
                  @click="deleteBlockEntry(record.id)"
                >
                  删除
                </a-button>
              </template>
            </template>
          </a-table>
        </div>
      </a-tab-pane>

      <!-- Audit logs (admin only) -->
      <a-tab-pane
        v-if="authStore.isAdmin()"
        key="audit"
        tab="审计日志"
      >
        <div class="whitelist-manager__section">
          <div class="whitelist-manager__filters">
            <a-select
              v-model:value="auditFilter.terminal_mode"
              placeholder="终端模式"
              allow-clear
              style="width: 150px"
              @change="loadAuditLogs"
            >
              <a-select-option value="local">本地终端</a-select-option>
              <a-select-option value="server">服务端终端</a-select-option>
            </a-select>
            <a-input
              v-model:value="auditFilter.session_id"
              placeholder="会话ID筛选"
              allow-clear
              style="width: 250px"
              @press-enter="loadAuditLogs"
            />
            <a-button @click="loadAuditLogs">刷新</a-button>
          </div>
          <a-table
            :data-source="auditLogs"
            :columns="auditColumns"
            :loading="auditLoading"
            :pagination="{ pageSize: 20 }"
            row-key="id"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'decision'">
                <a-tag :color="decisionColor(record.decision)">
                  {{ record.decision }}
                </a-tag>
              </template>
              <template v-if="column.key === 'terminal_mode'">
                <a-tag :color="record.terminal_mode === 'server' ? 'purple' : 'blue'">
                  {{ record.terminal_mode === 'server' ? '服务端' : '本地' }}
                </a-tag>
              </template>
            </template>
          </a-table>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  Tabs as ATabs,
  TabPane as ATabPane,
  Input as AInput,
  Button as AButton,
  Table as ATable,
  Alert as AAlert,
  Select as ASelect,
  SelectOption as ASelectOption,
  Tag as ATag,
} from 'ant-design-vue'
import { terminalApi } from '@/api/terminal'
import type {
  IWhitelistEntry,
  IBlocklistEntry,
  IAuditLogEntry,
} from '@/api/terminal'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

const activeTab = ref('user')

// ── User whitelist ──────────────────────────────────────────────────
const userWhitelist = ref<IWhitelistEntry[]>([])
const newUserPattern = ref('')
const userLoading = ref(false)

async function loadUserWhitelist(): Promise<void> {
  userLoading.value = true
  try {
    const resp = await terminalApi.listUserWhitelist()
    userWhitelist.value = resp.entries
  } catch (err) {
    message.error('加载用户白名单失败')
  } finally {
    userLoading.value = false
  }
}

async function addUserEntry(): Promise<void> {
  const pattern = newUserPattern.value.trim()
  if (!pattern) return
  userLoading.value = true
  try {
    await terminalApi.addUserWhitelist(pattern)
    newUserPattern.value = ''
    await loadUserWhitelist()
    message.success('已添加到白名单')
  } catch {
    message.error('添加失败')
  } finally {
    userLoading.value = false
  }
}

async function deleteUserEntry(id: string): Promise<void> {
  try {
    await terminalApi.deleteUserWhitelist(id)
    await loadUserWhitelist()
    message.success('已删除')
  } catch {
    message.error('删除失败')
  }
}

// ── Global whitelist ────────────────────────────────────────────────
const globalWhitelist = ref<IWhitelistEntry[]>([])
const newGlobalPattern = ref('')
const globalLoading = ref(false)

async function loadGlobalWhitelist(): Promise<void> {
  globalLoading.value = true
  try {
    const resp = await terminalApi.listGlobalWhitelist()
    globalWhitelist.value = resp.entries
  } catch {
    message.error('加载全局白名单失败')
  } finally {
    globalLoading.value = false
  }
}

async function addGlobalEntry(): Promise<void> {
  const pattern = newGlobalPattern.value.trim()
  if (!pattern) return
  globalLoading.value = true
  try {
    await terminalApi.addGlobalWhitelist(pattern)
    newGlobalPattern.value = ''
    await loadGlobalWhitelist()
    message.success('已添加到全局白名单')
  } catch {
    message.error('添加失败')
  } finally {
    globalLoading.value = false
  }
}

async function deleteGlobalEntry(id: string): Promise<void> {
  try {
    await terminalApi.deleteGlobalWhitelist(id)
    await loadGlobalWhitelist()
    message.success('已删除')
  } catch {
    message.error('删除失败')
  }
}

// ── Blocklist ───────────────────────────────────────────────────────
const blocklist = ref<IBlocklistEntry[]>([])
const newBlockPattern = ref('')
const newBlockReason = ref('')
const blockLoading = ref(false)

async function loadBlocklist(): Promise<void> {
  blockLoading.value = true
  try {
    const resp = await terminalApi.listBlocklist()
    blocklist.value = resp.entries
  } catch {
    message.error('加载黑名单失败')
  } finally {
    blockLoading.value = false
  }
}

async function addBlockEntry(): Promise<void> {
  const pattern = newBlockPattern.value.trim()
  if (!pattern) return
  blockLoading.value = true
  try {
    await terminalApi.addBlocklist(pattern, newBlockReason.value.trim() || '管理员禁止')
    newBlockPattern.value = ''
    newBlockReason.value = ''
    await loadBlocklist()
    message.success('已添加到黑名单')
  } catch {
    message.error('添加失败')
  } finally {
    blockLoading.value = false
  }
}

async function deleteBlockEntry(id: string): Promise<void> {
  try {
    await terminalApi.deleteBlocklist(id)
    await loadBlocklist()
    message.success('已删除')
  } catch {
    message.error('删除失败')
  }
}

// ── Audit logs ──────────────────────────────────────────────────────
const auditLogs = ref<IAuditLogEntry[]>([])
const auditLoading = ref(false)
const auditFilter = ref<{ terminal_mode?: string; session_id?: string }>({})

async function loadAuditLogs(): Promise<void> {
  auditLoading.value = true
  try {
    const resp = await terminalApi.listAuditLogs({
      terminal_mode: auditFilter.value.terminal_mode || undefined,
      session_id: auditFilter.value.session_id || undefined,
      limit: 100,
    })
    auditLogs.value = resp.entries
  } catch {
    message.error('加载审计日志失败')
  } finally {
    auditLoading.value = false
  }
}

// ── Table columns ───────────────────────────────────────────────────
const whitelistColumns = [
  { title: '命令模式', dataIndex: 'command_pattern', key: 'command_pattern' },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 200 },
  { title: '操作', key: 'action', width: 80 },
]

const blocklistColumns = [
  { title: '命令模式', dataIndex: 'command_pattern', key: 'command_pattern' },
  { title: '原因', dataIndex: 'reason', key: 'reason' },
  { title: '创建时间', dataIndex: 'created_at', key: 'created_at', width: 200 },
  { title: '操作', key: 'action', width: 80 },
]

const auditColumns = [
  { title: '时间', dataIndex: 'created_at', key: 'created_at', width: 200 },
  { title: '用户', dataIndex: 'user_id', key: 'user_id', width: 120 },
  { title: '命令', dataIndex: 'command', key: 'command', ellipsis: true },
  { title: '决策', key: 'decision', width: 100 },
  { title: '模式', key: 'terminal_mode', width: 80 },
  { title: '退出码', dataIndex: 'exit_code', key: 'exit_code', width: 80 },
]

function decisionColor(decision: string): string {
  const colors: Record<string, string> = {
    executed: 'green',
    confirmed: 'blue',
    rejected: 'orange',
    blocked: 'red',
    denied: 'red',
    expired: 'default',
  }
  return colors[decision] || 'default'
}

// ── Init ────────────────────────────────────────────────────────────
onMounted(() => {
  loadUserWhitelist()
  if (authStore.isAdmin()) {
    loadGlobalWhitelist()
    loadBlocklist()
    loadAuditLogs()
  }
})
</script>

<style scoped>
.whitelist-manager {
  padding: var(--space-3);
  height: 100%;
  overflow-y: auto;
}

.whitelist-manager__section {
  padding-top: var(--space-3);
}

.whitelist-manager__add-form {
  display: flex;
  gap: var(--space-2);
  margin-bottom: var(--space-3);
}

.whitelist-manager__filters {
  display: flex;
  gap: var(--space-2);
  margin-bottom: var(--space-3);
  align-items: center;
}
</style>
