<script setup lang="ts">
import { ref, h, onMounted } from 'vue'
import { useMessage, NCard, NDataTable, NButton, NTag, NSpace, NModal, NForm, NFormItem, NSelect, NIcon, NInput } from 'naive-ui'
import { SaveOutline, SearchOutline, AddOutline } from '@vicons/ionicons5'
import { api } from '../../api/client'

interface PlatformMember {
  id: string
  email: string
  display_name: string
  platform_role: string
  last_login_at?: string
  created_at?: string
}

interface SearchUser {
  id: string
  email: string
  display_name: string
  platform_role?: string
}

const members = ref<PlatformMember[]>([])
const total = ref(0)
const loading = ref(false)

// Edit existing member
const showEditModal = ref(false)
const editing = ref<PlatformMember | null>(null)

// Add new member
const showAddModal = ref(false)
const searchQ = ref('')
const searchResults = ref<SearchUser[]>([])
const searching = ref(false)
const selectedUser = ref<SearchUser | null>(null)
const newRole = ref('platform_admin')

const roleOptions = [
  { label: '平台管理 (ADMIN)', value: 'platform_admin' },
  { label: '平台运营 (OPERATOR)', value: 'platform_operator' },
  { label: '平台只读 (VIEWER)', value: 'platform_viewer' },
]
const saving = ref(false)
const message = useMessage()

onMounted(loadData)

async function loadData() {
  loading.value = true
  try {
    const { data } = await api.get('/admin/platform-roles', { params: { page_size: 200 } })
    members.value = data.items
    total.value = data.total
  } catch (e) {
    message.error('加载平台用户列表失败：' + ((e as any)?.response?.data?.detail || '请重试'))
  } finally {
    loading.value = false
  }
}

function editRole(row: PlatformMember) {
  editing.value = { ...row }
  showEditModal.value = true
}

async function saveEdit() {
  if (!editing.value) return
  saving.value = true
  try {
    await api.put(`/admin/platform-roles/${editing.value.id}`, { role: editing.value.platform_role })
    showEditModal.value = false
    await loadData()
    message.success('角色已更新')
  } catch (e: any) {
    message.error('保存失败：' + (e.response?.data?.detail || '请重试'))
  } finally {
    saving.value = false
  }
}

async function removeRole(row: PlatformMember) {
  try {
    await api.delete(`/admin/platform-roles/${row.id}`)
    await loadData()
    message.success('已移除平台角色')
  } catch (e: any) {
    message.error('操作失败：' + (e.response?.data?.detail || '请重试'))
  }
}

function openAddModal() {
  searchQ.value = ''
  searchResults.value = []
  selectedUser.value = null
  newRole.value = 'platform_admin'
  showAddModal.value = true
}

async function searchUsers() {
  if (!searchQ.value.trim()) return
  selectedUser.value = null
  searching.value = true
  try {
    const { data } = await api.get('/admin/users', { params: { q: searchQ.value, page_size: 20 } })
    // 不过滤——让 owner 能看到所有用户，包含已有角色的
    searchResults.value = data.items || []
  } catch (e: any) {
    message.error('搜索失败：' + (e.response?.data?.detail || '请重试'))
  } finally {
    searching.value = false
  }
}

function pickUser(u: SearchUser) {
  selectedUser.value = u
}

async function saveAdd() {
  if (!selectedUser.value) {
    message.warning('请先在搜索结果中点击选择一个用户')
    return
  }
  if (!newRole.value) return
  const roleLabel = roleOptions.find(r => r.value === newRole.value)?.label || newRole.value
  const ok = window.confirm(`确认将 ${selectedUser.value.display_name}（${selectedUser.value.email}）设为「${roleLabel}」？`)
  if (!ok) return
  saving.value = true
  try {
    await api.put(`/admin/platform-roles/${selectedUser.value.id}`, { role: newRole.value })
    showAddModal.value = false
    await loadData()
    message.success(`已将 ${selectedUser.value.email} 设为 ${roleLabel}`)
  } catch (e: any) {
    message.error('分配失败：' + (e.response?.data?.detail || '请重试'))
  } finally {
    saving.value = false
  }
}

const roleBadge = (role: string) => {
  const map: Record<string, { type: 'error' | 'warning' | 'info' | 'default', label: string }> = {
    platform_owner: { type: 'error', label: 'OWNER' },
    platform_admin: { type: 'warning', label: 'ADMIN' },
    platform_operator: { type: 'info', label: 'OP' },
    platform_viewer: { type: 'default', label: 'VIEWER' },
  }
  return map[role] || { type: 'default', label: role }
}

const cols = [
  { title: '邮箱', key: 'email', width: 220, ellipsis: true },
  { title: '姓名', key: 'display_name', width: 100 },
  {
    title: '平台角色', key: 'platform_role', width: 100,
    render: (r: PlatformMember) => {
      const b = roleBadge(r.platform_role)
      return h(NTag, { size: 'tiny', type: b.type }, () => b.label)
    },
  },
  { title: '最后登录', key: 'last_login_at', width: 100, render: (r: PlatformMember) => r.last_login_at?.slice(0, 10) || '—' },
  {
    title: '操作', key: 'actions', width: 140,
    render: (r: PlatformMember) => {
      if (r.platform_role === 'platform_owner') return '—'
      return h(NSpace, null, () => [
        h(NButton, { size: 'tiny', onClick: () => editRole(r) }, () => '编辑'),
        h(NButton, { size: 'tiny', type: 'error', ghost: true, onClick: () => removeRole(r) }, () => '移除'),
      ])
    },
  },
]
const scrollX = 660
</script>

<template>
  <div>
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
      <h2 style="margin:0">👥 平台用户管理 ({{ total }})</h2>
      <NButton size="small" type="primary" @click="openAddModal" class="sky-btn">
        <template #icon><NIcon size="14"><AddOutline /></NIcon></template>添加
      </NButton>
    </div>
    <NCard :bordered="false">
      <p style="color:var(--text-muted);font-size:13px;margin-bottom:12px">
        管理平台成员的角色。修改后 JWT 不立即过期，下次登录生效。OWNER 角色不可在此编辑。
      </p>
      <NDataTable :columns="cols" :data="members" :loading="loading" size="small" :paginate="{ pageSize: 20 }" :scroll-x="scrollX" />
    </NCard>

    <!-- Edit Modal -->
    <NModal v-model:show="showEditModal" title="编辑平台角色" v-if="editing">
      <NCard style="width:400px">
        <NForm label-placement="left" label-width="80">
          <NFormItem label="邮箱">{{ editing.email }}</NFormItem>
          <NFormItem label="姓名">{{ editing.display_name }}</NFormItem>
          <NFormItem label="角色">
            <NSelect v-model:value="editing.platform_role" :options="roleOptions" />
          </NFormItem>
          <NButton type="primary" :loading="saving" attr-type="button" @click="saveEdit" class="sky-btn">
            <template #icon><NIcon size="14"><SaveOutline /></NIcon></template>保存
          </NButton>
        </NForm>
      </NCard>
    </NModal>

    <!-- Add Modal -->
    <NModal v-model:show="showAddModal" title="添加平台用户" preset="card" style="width:520px" closable>
      <div style="margin-bottom:14px">
        <div style="font-size:13px;font-weight:500;margin-bottom:6px">搜索用户</div>
        <div style="display:flex;gap:8px;width:100%">
          <NInput v-model:value="searchQ" placeholder="输入邮箱或姓名搜索" size="small" class="add-user-search" @keyup.enter="searchUsers" />
          <NButton size="small" :loading="searching" @click="searchUsers" class="sky-btn">
            <template #icon><NIcon size="14"><SearchOutline /></NIcon></template>搜索
          </NButton>
        </div>
      </div>

      <div v-if="searchResults.length" style="margin-bottom:14px">
        <div style="font-size:12px;color:var(--text-muted);margin-bottom:6px">搜索结果：</div>
        <div v-for="u in searchResults" :key="u.id" style="margin-bottom:4px">
          <div
            @click.stop="pickUser(u)"
            :style="{
              padding: '8px 12px',
              cursor: 'pointer',
              borderRadius: '4px',
              border: selectedUser?.id === u.id ? '2px solid var(--primary-color)' : '2px solid transparent',
              background: selectedUser?.id === u.id ? 'var(--primary-color)' : 'var(--bg-hover)',
              color: selectedUser?.id === u.id ? '#fff' : undefined,
              fontSize: '13px',
            }">
            <span style="font-weight:500">{{ u.display_name }}</span>
            <span style="margin-left:8px;opacity:0.7">{{ u.email }}</span>
            <span v-if="u.platform_role" style="margin-left:6px;font-size:11px;opacity:0.5">（已有角色：{{ u.platform_role }}）</span>
          </div>
        </div>
        <div style="font-size:12px;color:var(--text-muted);margin-top:4px">共 {{ searchResults.length }} 条结果</div>
      </div>
      <div v-else-if="searchQ && !searching" style="font-size:12px;color:var(--text-muted);margin-bottom:14px">
        未找到用户
      </div>

      <div v-if="selectedUser" style="margin-bottom:14px;background:var(--primary-color);color:#fff;padding:8px 12px;border-radius:4px;font-size:13px">
        已选：{{ selectedUser.display_name }}（{{ selectedUser.email }}）
      </div>

      <div style="margin-bottom:14px">
        <div style="font-size:13px;font-weight:500;margin-bottom:6px">分配角色</div>
        <NSelect v-model:value="newRole" :options="roleOptions" />
      </div>

      <NButton type="primary" :loading="saving" @click="saveAdd" class="sky-btn">
        <template #icon><NIcon size="14"><SaveOutline /></NIcon></template>确认分配
      </NButton>
    </NModal>
  </div>
</template>
