<script lang="ts" setup>
import { Icon } from '@iconify/vue'
import { toast } from 'vue-sonner'

import type { User } from '@/services/api/monisuo-admin.api'

import { BasicPage } from '@/components/global-layout'
import { useGetUserListQuery, useUpdateUserStatusMutation } from '@/services/api/monisuo-admin.api'

const pageNum = ref(1)
const pageSize = ref(10)
const searchUsername = ref('')
const searchStatus = ref<number | undefined>()
const searchStatusTemp = ref<number | string>('all')

const { data, isLoading, refetch } = useGetUserListQuery({
  pageNum: pageNum.value,
  pageSize: pageSize.value,
  username: searchUsername.value || undefined,
  status: searchStatus.value,
})

const updateStatusMutation = useUpdateUserStatusMutation()

const users = computed(() => data.value?.data?.list || [])
const total = computed(() => data.value?.data?.total || 0)
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

// 用户详情弹窗
const showDetailDialog = ref(false)
const selectedUser = ref<User | null>(null)

function viewUserDetail(user: User) {
  selectedUser.value = user
  showDetailDialog.value = true
}

async function toggleStatus(user: User) {
  const newStatus = user.status === 1 ? 0 : 1
  const action = newStatus === 0 ? '禁用' : '启用'

  try {
    await updateStatusMutation.mutateAsync({ userId: user.id, status: newStatus })
    toast.success(`已${action}用户 ${user.username}`)
  }
  catch (e: any) {
    toast.error(e.response?.data?.msg || `${action}失败`)
  }
}

function search() {
  searchStatus.value = searchStatusTemp.value === 'all' ? undefined : searchStatusTemp.value as number
  pageNum.value = 1
  refetch()
}

function resetSearch() {
  searchUsername.value = ''
  searchStatusTemp.value = 'all'
  searchStatus.value = undefined
  pageNum.value = 1
  refetch()
}

function handlePageChange(page: number) {
  pageNum.value = page
  refetch()
}

function handlePageSizeChange(size: unknown) {
  if (size === null || size === undefined)
    return
  pageSize.value = Number(size)
  pageNum.value = 1
  refetch()
}
</script>

<template>
  <BasicPage title="用户管理" description="管理系统用户">
    <div class="space-y-4">
      <!-- 搜索栏 -->
      <UiCard class="p-4">
        <div class="flex flex-col sm:flex-row gap-4">
          <div class="flex-1 grid gap-2">
            <UiLabel>用户名</UiLabel>
            <UiInput v-model="searchUsername" placeholder="搜索用户名" @keyup.enter="search" />
          </div>
          <div class="w-full sm:w-[160px] grid gap-2">
            <UiLabel>状态</UiLabel>
            <UiSelect v-model="searchStatusTemp">
              <UiSelectTrigger>
                <UiSelectValue placeholder="全部" />
              </UiSelectTrigger>
              <UiSelectContent>
                <UiSelectItem value="all">
                  全部
                </UiSelectItem>
                <UiSelectItem :value="1">
                  正常
                </UiSelectItem>
                <UiSelectItem :value="0">
                  禁用
                </UiSelectItem>
              </UiSelectContent>
            </UiSelect>
          </div>
          <div class="flex items-end gap-2">
            <UiButton @click="search">
              搜索
            </UiButton>
            <UiButton variant="outline" @click="resetSearch">
              重置
            </UiButton>
          </div>
        </div>
      </UiCard>

      <!-- PC端表格 -->
      <UiCard class="hidden md:block overflow-x-auto p-4">
        <UiTable>
          <UiTableHeader>
            <UiTableRow>
              <UiTableHead class="w-[80px]">
                ID
              </UiTableHead>
              <UiTableHead>用户名</UiTableHead>
              <UiTableHead>昵称</UiTableHead>
              <UiTableHead class="hidden lg:table-cell">
                手机
              </UiTableHead>
              <UiTableHead class="hidden xl:table-cell">
                邮箱
              </UiTableHead>
              <UiTableHead>状态</UiTableHead>
              <UiTableHead class="hidden sm:table-cell">
                注册时间
              </UiTableHead>
              <UiTableHead class="text-right">
                操作
              </UiTableHead>
            </UiTableRow>
          </UiTableHeader>
          <UiTableBody>
            <UiTableRow v-if="isLoading">
              <UiTableCell :col-span="8" class="text-center py-8">
                <UiSpinner class="mx-auto" />
              </UiTableCell>
            </UiTableRow>
            <UiTableRow v-else-if="users.length === 0">
              <UiTableCell :col-span="8" class="text-center py-8 text-muted-foreground">
                暂无数据
              </UiTableCell>
            </UiTableRow>
            <UiTableRow v-for="user in users" :key="user.id">
              <UiTableCell>{{ user.id }}</UiTableCell>
              <UiTableCell class="font-medium">
                {{ user.username }}
              </UiTableCell>
              <UiTableCell>{{ user.nickname || '-' }}</UiTableCell>
              <UiTableCell class="hidden lg:table-cell">
                {{ user.phone || '-' }}
              </UiTableCell>
              <UiTableCell class="hidden xl:table-cell">
                {{ user.email || '-' }}
              </UiTableCell>
              <UiTableCell>
                <UiBadge :variant="user.status === 1 ? 'default' : 'destructive'">
                  {{ user.status === 1 ? '正常' : '禁用' }}
                </UiBadge>
              </UiTableCell>
              <UiTableCell class="hidden sm:table-cell text-muted-foreground text-sm">
                {{ user.createTime }}
              </UiTableCell>
              <UiTableCell class="text-right">
                <div class="flex justify-end gap-2">
                  <UiButton size="sm" variant="ghost" @click="viewUserDetail(user)">
                    <Icon icon="lucide:eye" class="size-4" />
                  </UiButton>
                  <UiButton
                    size="sm"
                    variant="outline"
                    :disabled="updateStatusMutation.isPending.value"
                    @click="toggleStatus(user)"
                  >
                    {{ user.status === 1 ? '禁用' : '启用' }}
                  </UiButton>
                </div>
              </UiTableCell>
            </UiTableRow>
          </UiTableBody>
        </UiTable>
      </UiCard>

      <!-- 移动端卡片列表 -->
      <div class="md:hidden space-y-3">
        <div v-if="isLoading" class="text-center py-8">
          <UiSpinner class="mx-auto" />
        </div>
        <template v-else-if="users.length > 0">
          <UiCard v-for="user in users" :key="user.id" class="p-4">
            <div class="flex items-start justify-between">
              <div class="space-y-1">
                <div class="font-medium">
                  {{ user.username }}
                </div>
                <div class="text-sm text-muted-foreground">
                  {{ user.nickname || '未设置昵称' }}
                </div>
              </div>
              <UiBadge :variant="user.status === 1 ? 'default' : 'destructive'">
                {{ user.status === 1 ? '正常' : '禁用' }}
              </UiBadge>
            </div>
            <div class="mt-3 pt-3 border-t text-sm text-muted-foreground space-y-1">
              <div v-if="user.phone">
                手机: {{ user.phone }}
              </div>
              <div>注册: {{ user.createTime }}</div>
            </div>
            <div class="mt-3 flex gap-2">
              <UiButton size="sm" variant="outline" class="flex-1" @click="viewUserDetail(user)">
                查看详情
              </UiButton>
              <UiButton
                size="sm"
                variant="outline"
                class="flex-1"
                :disabled="updateStatusMutation.isPending.value"
                @click="toggleStatus(user)"
              >
                {{ user.status === 1 ? '禁用' : '启用' }}
              </UiButton>
            </div>
          </UiCard>
        </template>
        <div v-else class="text-center py-8 text-muted-foreground">
          暂无数据
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="total > 0" class="flex flex-col sm:flex-row items-center justify-between gap-4 px-2">
        <div class="text-sm text-muted-foreground">
          共 {{ total }} 条记录
        </div>
        <div class="flex items-center gap-4">
          <div class="flex items-center gap-2">
            <span class="text-sm">每页</span>
            <UiSelect :model-value="`${pageSize}`" @update:model-value="handlePageSizeChange">
              <UiSelectTrigger class="h-8 w-[70px]">
                <UiSelectValue />
              </UiSelectTrigger>
              <UiSelectContent>
                <UiSelectItem value="10">
                  10
                </UiSelectItem>
                <UiSelectItem value="20">
                  20
                </UiSelectItem>
                <UiSelectItem value="50">
                  50
                </UiSelectItem>
              </UiSelectContent>
            </UiSelect>
            <span class="text-sm">条</span>
          </div>
          <div class="flex items-center gap-2">
            <UiButton
              variant="outline"
              size="icon"
              class="h-8 w-8"
              :disabled="pageNum <= 1"
              @click="handlePageChange(pageNum - 1)"
            >
              <Icon icon="lucide:chevron-left" class="size-4" />
            </UiButton>
            <span class="text-sm min-w-[80px] text-center">
              {{ pageNum }} / {{ totalPages }}
            </span>
            <UiButton
              variant="outline"
              size="icon"
              class="h-8 w-8"
              :disabled="pageNum >= totalPages"
              @click="handlePageChange(pageNum + 1)"
            >
              <Icon icon="lucide:chevron-right" class="size-4" />
            </UiButton>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户详情弹窗 -->
    <UiDialog v-model:open="showDetailDialog">
      <UiDialogContent class="max-w-md">
        <UiDialogHeader>
          <UiDialogTitle>用户详情</UiDialogTitle>
        </UiDialogHeader>
        <div v-if="selectedUser" class="space-y-4">
          <div class="grid grid-cols-3 gap-2 text-sm">
            <div class="text-muted-foreground">
              用户ID
            </div>
            <div class="col-span-2 font-medium">
              {{ selectedUser.id }}
            </div>

            <div class="text-muted-foreground">
              用户名
            </div>
            <div class="col-span-2 font-medium">
              {{ selectedUser.username }}
            </div>

            <div class="text-muted-foreground">
              昵称
            </div>
            <div class="col-span-2">
              {{ selectedUser.nickname || '-' }}
            </div>

            <div class="text-muted-foreground">
              手机
            </div>
            <div class="col-span-2">
              {{ selectedUser.phone || '-' }}
            </div>

            <div class="text-muted-foreground">
              邮箱
            </div>
            <div class="col-span-2">
              {{ selectedUser.email || '-' }}
            </div>

            <div class="text-muted-foreground">
              状态
            </div>
            <div class="col-span-2">
              <UiBadge :variant="selectedUser.status === 1 ? 'default' : 'destructive'">
                {{ selectedUser.status === 1 ? '正常' : '禁用' }}
              </UiBadge>
            </div>

            <div class="text-muted-foreground">
              注册时间
            </div>
            <div class="col-span-2">
              {{ selectedUser.createTime }}
            </div>

            <div class="text-muted-foreground">
              更新时间
            </div>
            <div class="col-span-2">
              {{ selectedUser.updateTime }}
            </div>
          </div>
        </div>
        <UiDialogFooter>
          <UiButton variant="outline" @click="showDetailDialog = false">
            关闭
          </UiButton>
        </UiDialogFooter>
      </UiDialogContent>
    </UiDialog>
  </BasicPage>
</template>
