<template>
  <div>
    <h1 class="text-2xl font-bold mb-6">用户管理</h1>

    <UCard>
      <div class="flex gap-4 mb-4">
        <USelect
          v-model="roleFilter"
          :options="roleOptions"
          class="w-40"
        />
        <UButton
          variant="ghost"
          icon="i-heroicons-arrow-path"
          @click="refresh"
          :loading="loading"
        >
          刷新
        </UButton>
      </div>

      <UTable
        :columns="columns"
        :rows="users"
        :loading="loading"
        hover
      >
        <template #user-data="{ row }">
          <div class="flex items-center gap-3">
            <UAvatar
              :src="row.avatarUrl"
              :alt="row.displayName || row.username"
            />
            <div>
              <p class="font-medium">{{ row.displayName || row.username }}</p>
              <p class="text-sm text-gray-500">{{ row.email }}</p>
            </div>
          </div>
        </template>

        <template #role-data="{ row }">
          <UBadge
            :label="roleLabels[row.role]"
            :color="roleColors[row.role]"
            size="xs"
          />
        </template>

        <template #isActive-data="{ row }">
          <UBadge
            :label="row.isActive ? '激活' : '禁用'"
            :color="row.isActive ? 'green' : 'red'"
            size="xs"
          />
        </template>

        <template #actions-data="{ row }">
          <div class="flex items-center gap-2">
            <UButton
              variant="ghost"
              size="xs"
              icon="i-heroicons-pencil"
              @click="editUser(row)"
            />
            <UButton
              variant="ghost"
              size="xs"
              icon="i-heroicons-trash"
              color="red"
              @click="confirmDelete(row)"
            />
          </div>
        </template>
      </UTable>

      <div v-if="totalPages > 1" class="mt-4 flex justify-center">
        <UPagination
          v-model="page"
          :total="total"
          :page-size="limit"
        />
      </div>
    </UCard>

    <UModal v-model="deleteModalOpen">
      <UCard>
        <template #header>
          <h3 class="text-lg font-semibold">确认删除</h3>
        </template>
        <p>确定要删除用户 "{{ selectedUser?.displayName || selectedUser?.username }}" 吗？此操作不可撤销。</p>
        <template #footer>
          <div class="flex gap-4">
            <UButton variant="ghost" @click="deleteModalOpen = false">取消</UButton>
            <UButton color="red" @click="deleteUser" :loading="deleting">删除</UButton>
          </div>
        </template>
      </UCard>
    </UModal>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'admin',
  middleware: ['admin'],
})

const { get, delete: deleteRequest } = useApi()

const users = ref<any[]>([])
const loading = ref(true)
const page = ref(1)
const limit = 20
const total = ref(0)
const totalPages = ref(0)

const roleFilter = ref('')

const deleteModalOpen = ref(false)
const selectedUser = ref<any>(null)
const deleting = ref(false)

const columns = [
  { key: 'user', label: '用户' },
  { key: 'role', label: '角色' },
  { key: 'isActive', label: '状态' },
  { key: 'createdAt', label: '注册时间' },
  { key: 'actions', label: '操作' },
]

const roleOptions = [
  { label: '全部角色', value: '' },
  { label: '管理员', value: 'admin' },
  { label: '版主', value: 'moderator' },
  { label: '用户', value: 'user' },
]

const roleLabels: Record<string, string> = {
  admin: '管理员',
  moderator: '版主',
  user: '用户',
}

const roleColors: Record<string, string> = {
  admin: 'red',
  moderator: 'yellow',
  user: 'blue',
}

const loadUsers = async () => {
  loading.value = true
  try {
    const query = new URLSearchParams()
    query.set('page', page.value.toString())
    query.set('limit', limit.toString())
    if (roleFilter.value) query.set('role', roleFilter.value)

    const response = await get(`/admin/users?${query}`)
    users.value = response.items
    total.value = response.total
    totalPages.value = response.totalPages
  } catch (error) {
    console.error('Failed to load users:', error)
  } finally {
    loading.value = false
  }
}

const refresh = () => {
  loadUsers()
}

const editUser = (user: any) => {
  // TODO: 打开编辑弹窗
  console.log('Edit user:', user)
}

const confirmDelete = (user: any) => {
  selectedUser.value = user
  deleteModalOpen.value = true
}

const deleteUser = async () => {
  if (!selectedUser.value) return
  deleting.value = true
  try {
    await deleteRequest(`/admin/users/${selectedUser.value.id}`)
    deleteModalOpen.value = false
    selectedUser.value = null
    await loadUsers()
  } catch (error) {
    console.error('Failed to delete user:', error)
  } finally {
    deleting.value = false
  }
}

watch([page, roleFilter], loadUsers)

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