<script setup lang="ts">
import { Ban, Loader2, Plus, Users } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import type { User } from '@/pages/agent/users/data/schema'

import ConfirmDialog from '@/components/confirm-dialog.vue'
import { BasicPage } from '@/components/global-layout'
import DataTable from '@/pages/agent/users/components/data-table.vue'
import api from '@/services/api'

const { t } = useI18n()
const router = useRouter()

const loading = ref(true)
const users = ref<User[]>([])
const tableRef = ref()
const searchFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const activeCount = ref(0)
const disabledCount = ref(0)
const bannedCount = ref(0)

const statusDialogOpen = ref(false)
const statusTarget = ref<User | null>(null)
const statusAction = ref<'ban' | 'unban'>('ban')

const serverPagination = computed(() => ({
  page: currentPage.value,
  pageSize: pageSize.value,
  total: total.value,
  onPageChange: (newPage: number) => {
    currentPage.value = newPage
    fetchUsers()
  },
  onPageSizeChange: (newPageSize: number) => {
    pageSize.value = newPageSize
    currentPage.value = 1
    fetchUsers()
  },
}))

async function fetchUsers() {
  loading.value = true
  try {
    const params = new URLSearchParams()
    params.append('page', String(currentPage.value))
    params.append('page_size', String(pageSize.value))
    if (searchFilter.value) {
      params.append('search', searchFilter.value.trim())
    }

    const data = await api.get<any>(`/agent/users?${params.toString()}`)
    users.value = data?.users || []
    total.value = data?.total || 0
    activeCount.value = data?.active_count || 0
    disabledCount.value = data?.disabled_count || 0
    bannedCount.value = data?.banned_count || 0
  }
  catch (error) {
    console.error('Load users failed:', error)
    users.value = []
  }
  finally {
    loading.value = false
  }
}

function goToCreate() {
  router.push('/agent/users/create')
}

function goToEdit(user: User) {
  router.push(`/agent/users/${user.id}`)
}

function toggleUserStatus(user: User) {
  statusTarget.value = user
  statusAction.value = user.status === 'banned' ? 'unban' : 'ban'
  statusDialogOpen.value = true
}

async function handleToggleStatus() {
  if (!statusTarget.value) return

  const newStatus = statusAction.value === 'ban' ? 'banned' : 'active'
  try {
    await api.put(`/agent/users/${statusTarget.value.id}/status`, { status: newStatus })
    toast.success(t('agent.users.statusUpdateSuccess'))
    fetchUsers()
  }
  catch (error: any) {
    console.error('切换用户状态失败:', error)
    toast.error(error.message || t('agent.users.statusUpdateFailed'))
  }
  finally {
    statusTarget.value = null
  }
}

onMounted(() => {
  fetchUsers()
})
</script>

<template>
  <BasicPage
    :title="t('agent.users.title')"
    :description="t('agent.users.description')"
    :breadcrumbs="[
      { title: t('nav.dashboard'), href: '/agent' },
      { title: t('nav.users') },
    ]"
    sticky
  >
    <template #actions>
      <UiButton @click="goToCreate">
        <Plus class="mr-2 h-4 w-4" />
        {{ t('agent.users.addUser') }}
      </UiButton>
    </template>

    <div class="space-y-6">
      <div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('agent.users.totalUsers') }}
            </UiCardTitle>
            <Users class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ total }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('agent.users.status.active') }}
            </UiCardTitle>
            <Users class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ activeCount }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('agent.users.status.disabled') }}
            </UiCardTitle>
            <Users class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ disabledCount }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              {{ t('agent.users.status.banned') }}
            </UiCardTitle>
            <Ban class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ bannedCount }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <div v-if="loading" class="flex items-center justify-center py-12">
            <Loader2 class="size-8 animate-spin text-muted-foreground" />
          </div>

          <DataTable
            v-else
            ref="tableRef"
            :loading
            :data="users"
            :server-pagination="serverPagination"
            :search-filter="searchFilter"
            :on-edit="goToEdit"
            :on-toggle-status="toggleUserStatus"
            @refresh="fetchUsers"
            @update:search-filter="searchFilter = $event; currentPage = 1; fetchUsers()"
          />
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="statusDialogOpen"
      :destructive="statusAction === 'ban'"
      :confirm-button-text="statusAction === 'ban' ? t('common.ban') : t('common.unban')"
      :cancel-button-text="t('common.cancel')"
      @confirm="handleToggleStatus"
    >
      <template #title>
        {{ statusAction === 'ban' ? t('agent.users.banUser') : t('agent.users.unbanUser') }}
      </template>
      <template #description>
        {{ statusAction === 'ban'
          ? t('agent.users.banConfirm', { username: statusTarget?.username })
          : t('agent.users.unbanConfirm', { username: statusTarget?.username })
        }}
      </template>
    </ConfirmDialog>
  </BasicPage>
</template>
