<script setup lang="ts">
import { computed, onMounted, reactive, shallowRef, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Edit } from '@element-plus/icons-vue'
import { createInvite, createUser, deleteInvite, fetchInvites, fetchUsers, updateUser } from '@/api/admin'
import type { User } from '@/types/api'

const users = shallowRef<User[]>([])
const invites = shallowRef<Record<string, unknown>[]>([])
const loading = shallowRef(false)
const userDialog = shallowRef(false)
const inviteDialog = shallowRef(false)
const detailMode = shallowRef<'create' | 'edit'>('create')
const editingUserId = shallowRef<number | null>(null)
const userForm = reactive({ name: '', email: '', password: '', role: 'user', is_active: true })
const inviteForm = reactive({ role: 'user', assigned_name: '', max_uses: 1 })

const userDialogTitle = computed(() => (detailMode.value === 'create' ? '创建用户' : '编辑用户'))
const roleLabels: Record<string, string> = {
  admin: '管理员',
  teacher: '老师',
  user: '用户',
}

watch(
  () => inviteForm.assigned_name,
  (name) => {
    if (name.trim()) {
      inviteForm.max_uses = 1
    }
  },
)

async function load() {
  loading.value = true
  try {
    users.value = (await fetchUsers()).data.items
    invites.value = (await fetchInvites()).data.items
  } finally {
    loading.value = false
  }
}

function openCreateUser() {
  detailMode.value = 'create'
  editingUserId.value = null
  userForm.name = ''
  userForm.email = ''
  userForm.password = ''
  userForm.role = 'user'
  userForm.is_active = true
  userDialog.value = true
}

function openEditUser(row: User) {
  detailMode.value = 'edit'
  editingUserId.value = row.id
  userForm.name = row.name
  userForm.email = row.email
  userForm.password = ''
  userForm.role = row.role
  userForm.is_active = row.is_active
  userDialog.value = true
}

async function saveUser() {
  if (detailMode.value === 'create') {
    await createUser(userForm)
    ElMessage.success('用户已创建')
  } else if (editingUserId.value !== null) {
    await updateUser(editingUserId.value, {
      name: userForm.name,
      email: userForm.email,
      role: userForm.role,
      is_active: userForm.is_active,
      password: userForm.password || undefined,
    })
    ElMessage.success('用户已更新')
  }
  userDialog.value = false
  await load()
}

async function toggleUser(row: User) {
  await updateUser(row.id, { is_active: !row.is_active })
  ElMessage.success(row.is_active ? '用户已禁用' : '用户已启用')
  await load()
}

async function resetPassword(row: User) {
  const { value } = await ElMessageBox.prompt('输入新密码', '重置密码', {
    inputType: 'password',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
  await updateUser(row.id, { password: value })
  ElMessage.success('密码已重置')
}

async function copyText(text: string, message: string) {
  if (navigator.clipboard && window.isSecureContext) {
    await navigator.clipboard.writeText(text)
  } else {
    const input = document.createElement('textarea')
    input.value = text
    input.style.position = 'fixed'
    input.style.opacity = '0'
    document.body.appendChild(input)
    input.select()
    document.execCommand('copy')
    document.body.removeChild(input)
  }
  ElMessage.success(message)
}

function registerLink(code: string) {
  return `${window.location.origin}/#/register?invite_code=${encodeURIComponent(code)}`
}

async function copyInviteCode(row: Record<string, unknown>) {
  await copyText(String(row.code ?? ''), '邀请码已复制')
}

async function copyInviteLink(row: Record<string, unknown>) {
  await copyText(registerLink(String(row.code ?? '')), '注册链接已复制')
}

async function removeInvite(row: Record<string, unknown>) {
  await ElMessageBox.confirm(`确定删除邀请码 ${String(row.code ?? '')} 吗？`, '删除邀请码', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning',
  })
  await deleteInvite(Number(row.id))
  ElMessage.success('邀请码已删除')
  await load()
}

async function saveInvite() {
  if (inviteForm.assigned_name.trim()) {
    inviteForm.max_uses = 1
  }
  await createInvite({
    role: inviteForm.role,
    assigned_name: inviteForm.assigned_name.trim() || undefined,
    max_uses: inviteForm.max_uses,
  })
  ElMessage.success('邀请码已创建')
  inviteDialog.value = false
  inviteForm.assigned_name = ''
  inviteForm.max_uses = 1
  await load()
}

onMounted(load)
</script>

<template>
  <section class="panel p-5">
    <div class="toolbar mb-4">
      <div class="flex-1">
        <h1 class="page-title">用户与权限</h1>
        <p class="muted text-sm mt-1">管理用户、角色和邀请码。</p>
      </div>
      <ElButton @click="inviteDialog = true">创建邀请码</ElButton>
      <ElButton type="primary" @click="openCreateUser">创建用户</ElButton>
    </div>

    <ElTabs>
      <ElTabPane label="用户">
        <ElTable v-loading="loading" :data="users" row-key="id">
          <ElTableColumn prop="name" label="姓名" />
          <ElTableColumn prop="email" label="邮箱" />
          <ElTableColumn prop="role" label="角色" width="120">
            <template #default="{ row }">
              {{ roleLabels[row.role] || row.role }}
            </template>
          </ElTableColumn>
          <ElTableColumn prop="is_active" label="状态" width="100">
            <template #default="{ row }">
              <ElTag :type="row.is_active ? 'success' : 'info'">{{ row.is_active ? '启用' : '禁用' }}</ElTag>
            </template>
          </ElTableColumn>
          <ElTableColumn label="操作" width="300" fixed="right">
            <template #default="{ row }">
              <ElButton :icon="Edit" size="small" @click="openEditUser(row)">编辑</ElButton>
              <ElButton size="small" @click="toggleUser(row)">{{ row.is_active ? '禁用' : '启用' }}</ElButton>
              <ElButton :icon="Delete" size="small" plain @click="resetPassword(row)">重置密码</ElButton>
            </template>
          </ElTableColumn>
        </ElTable>
      </ElTabPane>
      <ElTabPane label="邀请码">
        <ElTable :data="invites" row-key="id">
          <ElTableColumn prop="code" label="邀请码" />
          <ElTableColumn prop="role" label="角色">
            <template #default="{ row }">
              {{ roleLabels[String(row.role)] || row.role }}
            </template>
          </ElTableColumn>
          <ElTableColumn prop="assigned_name" label="指定姓名" min-width="120">
            <template #default="{ row }">
              {{ row.assigned_name || '-' }}
            </template>
          </ElTableColumn>
          <ElTableColumn prop="max_uses" label="可用次数" />
          <ElTableColumn prop="used_count" label="已使用" />
          <ElTableColumn label="操作" width="320" fixed="right">
            <template #default="{ row }">
              <ElButton size="small" @click="copyInviteCode(row)">复制分享码</ElButton>
              <ElButton size="small" type="primary" plain @click="copyInviteLink(row)">复制分享链接</ElButton>
              <ElButton :icon="Delete" size="small" type="danger" plain @click="removeInvite(row)">删除</ElButton>
            </template>
          </ElTableColumn>
        </ElTable>
      </ElTabPane>
    </ElTabs>
  </section>

  <ElDialog v-model="userDialog" :title="userDialogTitle" width="420px">
    <ElForm :model="userForm" label-position="top">
      <ElFormItem label="姓名"><ElInput v-model="userForm.name" /></ElFormItem>
      <ElFormItem label="邮箱"><ElInput v-model="userForm.email" /></ElFormItem>
      <ElFormItem label="密码">
        <ElInput v-model="userForm.password" type="password" show-password :placeholder="detailMode === 'create' ? '至少 6 位' : '留空则不修改'" />
      </ElFormItem>
      <ElFormItem label="角色">
        <ElSelect v-model="userForm.role" class="w-full">
          <ElOption label="管理员" value="admin" />
          <ElOption label="老师" value="teacher" />
          <ElOption label="用户" value="user" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="状态">
        <ElSwitch v-model="userForm.is_active" active-text="启用" inactive-text="禁用" />
      </ElFormItem>
    </ElForm>
    <template #footer><ElButton type="primary" @click="saveUser">保存</ElButton></template>
  </ElDialog>

  <ElDialog v-model="inviteDialog" title="创建邀请码" width="420px">
    <ElForm :model="inviteForm" label-position="top">
      <ElFormItem label="角色">
        <ElSelect v-model="inviteForm.role" class="w-full">
          <ElOption label="老师" value="teacher" />
          <ElOption label="用户" value="user" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="指定姓名">
        <ElInput v-model="inviteForm.assigned_name" placeholder="可选；填写后邀请码只能该姓名注册" />
      </ElFormItem>
      <ElFormItem label="可用次数">
        <ElInputNumber v-model="inviteForm.max_uses" :min="1" :disabled="Boolean(inviteForm.assigned_name.trim())" />
        <span v-if="inviteForm.assigned_name.trim()" class="invite-tip">指定姓名时固定为 1 次</span>
      </ElFormItem>
    </ElForm>
    <template #footer><ElButton type="primary" @click="saveInvite">生成</ElButton></template>
  </ElDialog>
</template>

<style scoped>
.invite-tip {
  margin-left: 10px;
  color: var(--qq-muted);
  font-size: 12px;
}
</style>
