<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref } from 'vue'

import { fetchRoles, deleteRole, type Role } from '@/features/admin/api/adminRoles'
import { useAdminTable } from '@/features/admin/composables/useAdminTable'

import AssignPermissionsDialog from './components/AssignPermissionsDialog.vue'
import RoleDialog from './components/RoleDialog.vue'

const showDialog = ref(false)
const editingRole = ref<Role | null>(null)
const showPermsDialog = ref(false)
const permsRole = ref<Role | null>(null)

const { loading, data: roles, load: loadRoles } = useAdminTable<Role[]>({
  fetchFn: fetchRoles,
})

function openCreate() {
  editingRole.value = null
  showDialog.value = true
}

function openEdit(row: Role) {
  editingRole.value = row
  showDialog.value = true
}

function openPerms(row: Role) {
  permsRole.value = row
  showPermsDialog.value = true
}

async function handleDelete(row: Role) {
  try {
    await ElMessageBox.confirm(`确定要删除角色「${row.name}」吗？已分配该角色的管理员将失去对应权限。`, '删除确认', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await deleteRole(row.id)
    ElMessage.success('角色已删除')
    await loadRoles()
  } catch {
    // 用户取消
  }
}
</script>

<template>
  <section class="page">
    <div class="page-header-row">
      <div class="page-header">
        <p class="eyebrow">Roles</p>
        <h1>角色管理</h1>
        <p>管理系统角色及其权限配置。</p>
      </div>
      <div class="toolbar-actions">
        <el-button @click="loadRoles">刷新</el-button>
        <el-button type="primary" @click="openCreate">新建角色</el-button>
      </div>
    </div>

    <el-table v-loading="loading" class="table-panel" :data="roles">
      <el-table-column prop="id" label="ID" width="70" />
      <el-table-column prop="code" label="编码" min-width="120" />
      <el-table-column prop="name" label="名称" min-width="120" />
      <el-table-column prop="description" label="描述" min-width="200" />
      <el-table-column prop="perm_count" label="权限数" width="90" align="center" />
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)">编辑</el-button>
          <el-button size="small" type="primary" @click="openPerms(row)">权限</el-button>
          <el-button
            v-if="row.code !== 'super_admin'"
            size="small"
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新建/编辑对话框 -->
    <RoleDialog
      v-model="showDialog"
      :role="editingRole"
      @saved="loadRoles"
    />

    <!-- 权限分配对话框 -->
    <AssignPermissionsDialog
      v-model="showPermsDialog"
      :role="permsRole"
      @saved="loadRoles"
    />
  </section>
</template>

<style scoped>
.toolbar-actions {
  display: flex;
  gap: 8px;
}
</style>
