<template>
  <div>
    <div class="flex items-center justify-between mb-6">
      <h2 class="text-xl font-bold text-gray-800">會員列表</h2>
      <div class="flex gap-2">
        <el-button type="primary" @click="showCreateDialog = true">新增會員</el-button>
        <el-button :loading="loading" @click="load" :icon="Refresh" size="small">重新整理</el-button>
      </div>
    </div>

    <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="members" stripe border class="w-full shadow-sm">
      <template #empty><el-empty description="目前無會員" /></template>
      <el-table-column prop="authentik_sub" label="Authentik Sub" min-width="260" />
      <el-table-column prop="email" label="Email" min-width="220" />
      <el-table-column prop="display_name" label="顯示名稱" min-width="180" />
      <el-table-column prop="is_active" label="啟用" width="100">
        <template #default="{ row }">{{ row.is_active ? '是' : '否' }}</template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button size="small" @click="openEdit(row)">編輯</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="showCreateDialog" title="新增會員" @close="resetCreateForm">
      <el-form ref="createFormRef" :model="createForm" :rules="createRules" label-width="120px">
        <el-form-item label="Authentik Sub" prop="authentik_sub"><el-input v-model="createForm.authentik_sub" /></el-form-item>
        <el-form-item label="Email" prop="email"><el-input v-model="createForm.email" /></el-form-item>
        <el-form-item label="顯示名稱" prop="display_name"><el-input v-model="createForm.display_name" /></el-form-item>
        <el-form-item label="啟用"><el-switch v-model="createForm.is_active" /></el-form-item>
        <el-form-item label="同步 Authentik"><el-switch v-model="createForm.sync_to_authentik" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" :loading="creating" @click="handleCreate">建立</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showEditDialog" title="編輯會員" @close="resetEditForm">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="Authentik Sub"><el-input :model-value="editForm.authentik_sub" disabled /></el-form-item>
        <el-form-item label="Email"><el-input v-model="editForm.email" /></el-form-item>
        <el-form-item label="顯示名稱"><el-input v-model="editForm.display_name" /></el-form-item>
        <el-form-item label="啟用"><el-switch v-model="editForm.is_active" /></el-form-item>
        <el-form-item label="同步 Authentik"><el-switch v-model="editForm.sync_to_authentik" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleEdit">儲存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getMembers, upsertMember, updateMember } from '@/api/members'

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

const showCreateDialog = ref(false)
const createFormRef = ref()
const creating = ref(false)
const createForm = ref({
  authentik_sub: '',
  email: '',
  display_name: '',
  is_active: true,
  sync_to_authentik: true
})
const createRules = {
  authentik_sub: [{ required: true, message: '請輸入 Authentik Sub', trigger: 'blur' }]
}

const showEditDialog = ref(false)
const saving = ref(false)
const editForm = ref({
  authentik_sub: '',
  email: '',
  display_name: '',
  is_active: true,
  sync_to_authentik: true
})

async function load() {
  loading.value = true
  error.value = false
  try {
    const res = await getMembers()
    members.value = res.data?.items || []
  } catch (err) {
    error.value = true
    errorMsg.value = err.response?.data?.detail || '載入失敗，請稍後再試'
  } finally {
    loading.value = false
  }
}

function resetCreateForm() {
  createForm.value = {
    authentik_sub: '',
    email: '',
    display_name: '',
    is_active: true,
    sync_to_authentik: true
  }
}

function openEdit(row) {
  editForm.value = {
    authentik_sub: row.authentik_sub,
    email: row.email || '',
    display_name: row.display_name || '',
    is_active: !!row.is_active,
    sync_to_authentik: true
  }
  showEditDialog.value = true
}

function resetEditForm() {
  editForm.value = {
    authentik_sub: '',
    email: '',
    display_name: '',
    is_active: true,
    sync_to_authentik: true
  }
}

async function handleCreate() {
  const valid = await createFormRef.value.validate().catch(() => false)
  if (!valid) return
  creating.value = true
  try {
    await upsertMember({ ...createForm.value })
    ElMessage.success('新增會員成功')
    showCreateDialog.value = false
    resetCreateForm()
    await load()
  } catch (err) {
    const detail = err.response?.data?.detail
    ElMessage.error(detail || '新增會員失敗')
  } finally {
    creating.value = false
  }
}

async function handleEdit() {
  saving.value = true
  try {
    await updateMember(editForm.value.authentik_sub, {
      email: editForm.value.email || null,
      display_name: editForm.value.display_name || null,
      is_active: editForm.value.is_active,
      sync_to_authentik: editForm.value.sync_to_authentik
    })
    ElMessage.success('更新會員成功')
    showEditDialog.value = false
    await load()
  } catch (err) {
    const detail = err.response?.data?.detail
    ElMessage.error(detail || '更新會員失敗')
  } finally {
    saving.value = false
  }
}

onMounted(load)
</script>
