<template>
  <section class="space-y-6">
    <ListSection
      :page="tab === 'staff' ? staffPage : activityPage"
      :total-pages="tab === 'staff' ? staffTotalPages : activityTotalPages"
      @prev="handlePrev"
      @next="handleNext"
    >
      <template #title>用户管理</template>
      <template #subtitle>管理运营成员与权限角色。</template>
      <template #filters>
        <div class="flex flex-wrap items-center gap-3">
          <div class="flex items-center gap-2 text-sm font-semibold">
            <button
              class="rounded-full px-3 py-1.5"
              :class="tab === 'staff' ? 'bg-mosquito-accent/10 text-mosquito-ink' : 'text-mosquito-ink/60'"
              data-test="tab-staff"
              @click="tab = 'staff'"
            >
              运营用户
            </button>
            <button
              class="rounded-full px-3 py-1.5"
              :class="tab === 'activity' ? 'bg-mosquito-accent/10 text-mosquito-ink' : 'text-mosquito-ink/60'"
              data-test="tab-activity"
              @click="switchToActivity()"
            >
              活动用户
            </button>
          </div>
          <div v-if="tab === 'staff'" class="flex flex-wrap items-center gap-2 text-xs text-mosquito-ink/70">
            <input class="mos-input !py-1 !px-2 !text-xs w-full md:w-56" v-model="staffQuery" placeholder="搜索姓名/邮箱" />
            <select class="mos-input !py-1 !px-2 !text-xs" v-model="roleFilter">
              <option value="">全部角色</option>
              <option value="admin">管理员</option>
              <option value="operator">运营</option>
              <option value="viewer">只读</option>
            </select>
            <select class="mos-input !py-1 !px-2 !text-xs" v-model="statusFilter">
              <option value="">全部状态</option>
              <option value="正常">正常</option>
              <option value="冻结">冻结</option>
            </select>
            <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="selectAllStaff">
              {{ allStaffSelected ? '取消全选' : '全选' }}
            </button>
            <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="batchEnable">批量启用</button>
            <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="batchDisable">批量禁用</button>
          </div>
          <div v-else class="flex flex-wrap items-center gap-3">
            <label class="text-xs text-mosquito-ink/70">活动</label>
            <select class="mos-input !py-1 !px-2 !text-xs" v-model.number="selectedActivityId" @change="loadActivityUsers">
              <option v-for="activity in activities" :key="activity.id" :value="activity.id">
                {{ activity.name }}
              </option>
            </select>
            <input class="mos-input !py-1 !px-2 !text-xs w-full md:w-56" v-model="activityQuery" placeholder="搜索昵称/手机号" />
            <select class="mos-input !py-1 !px-2 !text-xs" v-model="activityStatusFilter">
              <option value="">全部状态</option>
              <option value="已注册">已注册</option>
              <option value="未注册">未注册</option>
            </select>
            <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="loadActivityUsers">刷新</button>
          </div>
        </div>
      </template>
      <template #actions>
        <RouterLink v-if="tab === 'staff'" to="/users/invite" class="mos-btn mos-btn-accent">邀请用户</RouterLink>
      </template>
      <template #default>
        <div v-if="tab === 'staff'" class="space-y-3">
          <div
            v-for="user in pagedUsers"
            :key="user.id"
            class="flex items-center justify-between rounded-xl border border-mosquito-line px-4 py-3 transition hover:bg-mosquito-bg/60"
          >
            <div class="flex items-center gap-3">
              <input
                type="checkbox"
                class="h-4 w-4"
                :checked="selectedStaffIds.includes(user.id)"
                @click.stop
                @change.stop="toggleSelect(user.id)"
              />
              <RouterLink :to="`/users/${user.id}`" class="flex flex-col">
                <span class="text-sm font-semibold text-mosquito-ink">{{ user.name }}</span>
                <span class="mos-muted text-xs">{{ user.email }}</span>
              </RouterLink>
            </div>
            <div class="flex items-center gap-3 text-xs text-mosquito-ink/70">
              <span class="rounded-full bg-mosquito-accent/10 px-2 py-1 text-[10px] font-semibold text-mosquito-brand">{{ roleLabel(user.role) }}</span>
              <span>{{ user.status }}</span>
              <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click.stop="requestRole(user)">
                申请变更
              </button>
              <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click.stop="toggleUser(user)">
                {{ user.status === '冻结' ? '启用' : '禁用' }}
              </button>
            </div>
          </div>
        </div>
        <div v-else-if="pagedActivityUsers.length" class="space-y-3" data-test="activity-users-list">
          <div
            v-for="friend in pagedActivityUsers"
            :key="friend.nickname + friend.maskedPhone"
            data-test="activity-user-row"
            class="flex items-center justify-between rounded-xl border border-mosquito-line px-4 py-3"
          >
            <div>
              <div class="text-sm font-semibold text-mosquito-ink">{{ friend.nickname }}</div>
              <div class="mos-muted text-xs">{{ friend.maskedPhone }}</div>
            </div>
            <div class="text-xs text-mosquito-ink/70">{{ friend.status }}</div>
          </div>
        </div>
      </template>
      <template #empty>
        <div
          v-if="tab === 'activity' && !pagedActivityUsers.length"
          data-test="activity-users-empty"
          class="rounded-xl border border-dashed border-mosquito-line p-4 text-sm text-mosquito-ink/60"
        >
          暂无活动用户数据
        </div>
      </template>
    </ListSection>
  </section>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useDataService } from '../services'
import { RouterLink } from 'vue-router'
import { useAuditStore } from '../stores/audit'
import { useUserStore } from '../stores/users'
import { useActivityStore } from '../stores/activities'
import { useAuthStore } from '../stores/auth'
import ListSection from '../components/ListSection.vue'
import { RoleLabels, type AdminRole } from '../auth/roles'

type UserItem = {
  id: string
  name: string
  email: string
  role: string
  status: string
}

type ActivityUser = {
  nickname: string
  maskedPhone: string
  status: string
}

const users = ref<UserItem[]>([])
const service = useDataService()
const auditStore = useAuditStore()
const userStore = useUserStore()
const activityStore = useActivityStore()
const authStore = useAuthStore()
const tab = ref<'staff' | 'activity'>('staff')
const activityUsers = ref<ActivityUser[]>([])
const activities = ref<{ id: number; name: string }[]>([])
const selectedActivityId = ref<number>(0)
const staffQuery = ref('')
const roleFilter = ref('')
const statusFilter = ref('')
const selectedStaffIds = ref<string[]>([])
const activityQuery = ref('')
const activityStatusFilter = ref('')
const staffPage = ref(0)
const staffPageSize = 6
const activityPage = ref(0)
const activityPageSize = 6

onMounted(async () => {
  const [userList, invites, requests] = await Promise.all([
    service.getUsers(),
    service.getInvites(),
    service.getRoleRequests()
  ])
  users.value = userList
  userStore.init(userList, invites, requests)
  activities.value = activityStore.items.map((item) => ({ id: item.id, name: item.name }))
  selectedActivityId.value = activities.value[0]?.id ?? 0
})

const toggleUser = (user: UserItem) => {
  user.status = user.status === '冻结' ? '正常' : '冻结'
  auditStore.addLog(user.status === '冻结' ? '禁用用户' : '启用用户', user.name)
}

const requestRole = (user: UserItem) => {
  userStore.requestRoleChange(user.id, 'super_admin' as AdminRole, '需要更高权限')
  auditStore.addLog('提交角色变更申请', user.name)
}

const roleLabel = (role: string) => {
  return RoleLabels[role as AdminRole] || role
}

const resolveUserId = () => {
  const raw = authStore.user?.id ?? ''
  const parsed = Number(raw)
  return Number.isNaN(parsed) || parsed <= 0 ? 1 : parsed
}

const loadActivityUsers = async () => {
  if (!selectedActivityId.value) {
    activityUsers.value = []
    return
  }
  activityUsers.value = await service.getInvitedFriends(selectedActivityId.value, resolveUserId(), 0, 20)
}

const switchToActivity = async () => {
  tab.value = 'activity'
  await loadActivityUsers()
}

const handlePrev = () => {
  if (tab.value === 'staff') {
    staffPage.value -= 1
  } else {
    activityPage.value -= 1
  }
}

const handleNext = () => {
  if (tab.value === 'staff') {
    staffPage.value += 1
  } else {
    activityPage.value += 1
  }
}

const filteredUsers = computed(() => {
  return users.value.filter((user) => {
    const matchesQuery =
      user.name.includes(staffQuery.value) || user.email.includes(staffQuery.value)
    const matchesRole = roleFilter.value ? user.role === roleFilter.value : true
    const matchesStatus = statusFilter.value ? user.status === statusFilter.value : true
    return matchesQuery && matchesRole && matchesStatus
  })
})

watch([staffQuery, roleFilter, statusFilter], () => {
  staffPage.value = 0
})

const staffTotalPages = computed(() => Math.max(1, Math.ceil(filteredUsers.value.length / staffPageSize)))

const pagedUsers = computed(() => {
  const start = staffPage.value * staffPageSize
  return filteredUsers.value.slice(start, start + staffPageSize)
})

const allStaffSelected = computed(() => {
  return filteredUsers.value.length > 0 && filteredUsers.value.every((user) => selectedStaffIds.value.includes(user.id))
})

const toggleSelect = (id: string) => {
  if (selectedStaffIds.value.includes(id)) {
    selectedStaffIds.value = selectedStaffIds.value.filter((item) => item !== id)
  } else {
    selectedStaffIds.value = [...selectedStaffIds.value, id]
  }
}

const selectAllStaff = () => {
  if (allStaffSelected.value) {
    selectedStaffIds.value = []
  } else {
    selectedStaffIds.value = filteredUsers.value.map((user) => user.id)
  }
}

const batchEnable = () => {
  selectedStaffIds.value.forEach((id) => {
    const user = users.value.find((item) => item.id === id)
    if (user && user.status === '冻结') {
      toggleUser(user)
    }
  })
}

const batchDisable = () => {
  selectedStaffIds.value.forEach((id) => {
    const user = users.value.find((item) => item.id === id)
    if (user && user.status === '正常') {
      toggleUser(user)
    }
  })
}

const filteredActivityUsers = computed(() => {
  return activityUsers.value.filter((item) => {
    const matchesQuery =
      item.nickname.includes(activityQuery.value) || item.maskedPhone.includes(activityQuery.value)
    const matchesStatus = activityStatusFilter.value ? item.status === activityStatusFilter.value : true
    return matchesQuery && matchesStatus
  })
})

watch([activityQuery, activityStatusFilter], () => {
  activityPage.value = 0
})

const activityTotalPages = computed(() => Math.max(1, Math.ceil(filteredActivityUsers.value.length / activityPageSize)))

const pagedActivityUsers = computed(() => {
  const start = activityPage.value * activityPageSize
  return filteredActivityUsers.value.slice(start, start + activityPageSize)
})
</script>
