<template>
  <div>
    <div class="flex items-center justify-between mb-6">
      <h2 class="text-xl font-bold text-gray-800">系統管理（Keycloak 唯一來源）</h2>
      <div class="flex gap-2">
        <el-button :loading="syncing" @click="handleSync">同步 Keycloak</el-button>
        <el-button :loading="loading" @click="load">重新整理</el-button>
      </div>
    </div>

    <el-alert type="info" :closable="false" show-icon class="mb-4">
      <template #title>
        系統與角色請在 Keycloak 建立與調整，member 後台只做顯示與關聯。
      </template>
    </el-alert>

    <el-alert v-if="error" :title="errorMsg" type="error" show-icon :closable="false" class="mb-4" />
    <el-skeleton v-if="loading" :rows="4" animated />

    <el-table v-else :data="systems" stripe border class="w-full shadow-sm">
      <template #empty><el-empty description="目前無系統" /></template>
      <el-table-column prop="system_key" label="System Key" width="200" />
      <el-table-column prop="name" label="系統名稱" min-width="180" />
      <el-table-column prop="idp_client_id" label="Keycloak Client ID" min-width="220" />
      <el-table-column prop="status" label="狀態" width="110" />
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button size="small" @click="openRoles(row)">角色</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="showRolesDialog" :title="`系統角色：${selectedSystemLabel}`" width="980px">
      <el-table :data="systemRoles" border stripe v-loading="rolesLoading">
        <template #empty><el-empty description="此系統目前沒有角色" /></template>
        <el-table-column prop="role_key" label="Role Key" width="200" />
        <el-table-column prop="name" label="角色名稱" min-width="200" />
        <el-table-column prop="idp_role_name" label="Keycloak Role" min-width="210" />
        <el-table-column prop="status" label="狀態" width="110" />
      </el-table>
      <template #footer>
        <el-button @click="showRolesDialog = false">關閉</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { adminHttp } from '@/api/http'
import { getSystems, getSystemRoles } from '@/api/systems'

const systems = ref([])
const loading = ref(false)
const syncing = ref(false)
const error = ref(false)
const errorMsg = ref('')

const showRolesDialog = ref(false)
const selectedSystemLabel = ref('')
const systemRoles = ref([])
const rolesLoading = ref(false)

async function load() {
  loading.value = true
  error.value = false
  try {
    const res = await getSystems()
    systems.value = res.data?.items || []
  } catch (err) {
    error.value = true
    errorMsg.value = err.response?.data?.detail || '載入系統失敗'
  } finally {
    loading.value = false
  }
}

async function handleSync() {
  syncing.value = true
  try {
    const res = await adminHttp.post('/admin/sync/from-keycloak', null, { params: { force: true } })
    const summary = [
      `systems +${res.data?.systems_created ?? 0}`,
      `roles +${res.data?.roles_created ?? 0}`,
      `users upsert ${res.data?.users_upserted ?? 0}`
    ].join(' / ')
    ElMessage.success(`同步完成：${summary}`)
    await load()
  } catch (err) {
    ElMessage.error(err.response?.data?.detail || '同步失敗')
  } finally {
    syncing.value = false
  }
}

async function openRoles(row) {
  selectedSystemLabel.value = `${row.name} (${row.system_key})`
  showRolesDialog.value = true
  rolesLoading.value = true
  try {
    const res = await getSystemRoles(row.system_key)
    systemRoles.value = res.data?.roles || []
  } catch (_err) {
    ElMessage.error('載入系統角色失敗')
    systemRoles.value = []
  } finally {
    rolesLoading.value = false
  }
}

onMounted(load)
</script>
