<script setup lang="ts">
import AdminPageHeader from '@/components/admin/AdminPageHeader.vue'

import AdminUsersFilterSection from './components/AdminUsersFilterSection.vue'
import AdminUsersTable from './components/AdminUsersTable.vue'
import { useAdminUsers } from './composables/useAdminUsers'

const {
  loading,
  creating,
  actionLoadingId,
  errorMessage,
  items,
  pagination,
  // filter
  username,
  role,
  status,
  // create
  createUsername,
  createPassword,
  createRole,
  // actions
  loadUsers,
  submitCreate,
  updateRole,
  toggleStatus,
  promptResetPassword,
  promptUpdateInventoryGroups,
  // formatters
  isCurrentUser,
  formatRoleLabel,
  formatInventoryGroups,
  // utils
  hasAdminRole,
  formatAdminDateTime,
} = useAdminUsers()
</script>

<template>
  <div class="users-page list-page">
    <AdminPageHeader
      title="后台用户"
      description="管理员可维护后台账号、角色和启停状态，避免继续使用单一口令。"
    />

    <el-result v-if="!hasAdminRole('admin')" icon="warning" title="仅管理员可以访问用户管理。" />

    <template v-else>
      <AdminUsersFilterSection
        v-model:username="username"
        v-model:role="role"
        v-model:status="status"
        v-model:create-username="createUsername"
        v-model:create-password="createPassword"
        v-model:create-role="createRole"
        :creating="creating"
        :load-users="loadUsers"
        :submit-create="submitCreate"
      />

      <el-alert
        v-if="errorMessage"
        :title="errorMessage"
        type="error"
        show-icon
        :closable="false"
        class="mt-4"
      />

      <AdminUsersTable
        :loading="loading"
        :items="items"
        :pagination="pagination"
        :action-loading-id="actionLoadingId"
        :load-users="loadUsers"
        :is-current-user="isCurrentUser"
        :update-role="updateRole"
        :toggle-status="toggleStatus"
        :prompt-reset-password="promptResetPassword"
        :prompt-update-inventory-groups="promptUpdateInventoryGroups"
        :format-role-label="formatRoleLabel"
        :format-inventory-groups="formatInventoryGroups"
        :format-admin-date-time="formatAdminDateTime"
      />
    </template>
  </div>
</template>

<style scoped>
@import '../../styles/admin-list-pages.css';
</style>
