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

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

import ConfirmDialog from '@/components/confirm-dialog.vue'
import DateRangeFilter from '@/components/data-table/date-range-filter.vue'
import SingleFilter from '@/components/data-table/single-filter.vue'
import { BasicPage } from '@/components/global-layout'
import DataTable from '@/pages/admin/users/components/data-table.vue'
import api from '@/services/api'

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

interface Application {
  id: number
  name: string
}

const loading = ref(true)
const users = ref<User[]>([])
const tableRef = ref()
const applications = ref<Application[]>([])

const appFilter = ref<string>('')
const statusFilter = ref<string>('')
const accountStatusFilter = ref<string>('')
const lastLoginStartDate = ref<string>('')
const lastLoginEndDate = ref<string>('')
const createdStartDate = ref<string>('')
const createdEndDate = ref<string>('')

const deleteDialogOpen = ref(false)
const deleteTarget = ref<User | null>(null)
const batchDeleteDialogOpen = ref(false)
const batchDeleteIds = ref<(string | number)[]>([])

const filteredUsers = computed(() => {
  let result = users.value

  if (appFilter.value) {
    result = result.filter(user => String(user.application_id) === appFilter.value)
  }

  if (statusFilter.value) {
    result = result.filter(user => user.online_status === statusFilter.value)
  }

  if (accountStatusFilter.value) {
    result = result.filter(user => user.status === accountStatusFilter.value)
  }

  if (lastLoginStartDate.value) {
    const fromDateTime = lastLoginStartDate.value.includes('T')
      ? lastLoginStartDate.value.replace('T', ' ')
      : `${lastLoginStartDate.value} 00:00`
    result = result.filter((user) => {
      if (!user.last_login_at)
        return false
      return user.last_login_at >= fromDateTime
    })
  }

  if (lastLoginEndDate.value) {
    const toDateTime = lastLoginEndDate.value.includes('T')
      ? lastLoginEndDate.value.replace('T', ' ')
      : `${lastLoginEndDate.value} 23:59`
    result = result.filter((user) => {
      if (!user.last_login_at)
        return false
      return user.last_login_at <= toDateTime
    })
  }

  if (createdStartDate.value) {
    const fromDateTime = createdStartDate.value.includes('T')
      ? createdStartDate.value.replace('T', ' ')
      : `${createdStartDate.value} 00:00`
    result = result.filter(user => user.created_at >= fromDateTime)
  }

  if (createdEndDate.value) {
    const toDateTime = createdEndDate.value.includes('T')
      ? createdEndDate.value.replace('T', ' ')
      : `${createdEndDate.value} 23:59`
    result = result.filter(user => user.created_at <= toDateTime)
  }

  return result
})

const onlineCount = computed(() => filteredUsers.value.filter(user => user.online_status === 'online').length)
const offlineCount = computed(() => filteredUsers.value.filter(user => user.online_status === 'offline').length)
const bannedCount = computed(() => filteredUsers.value.filter(user => user.status === 'banned').length)

const applicationOptions = computed(() => {
  return applications.value.map(app => ({
    label: app.name,
    value: String(app.id),
  }))
})

const statusOptions = computed(() => [
  { label: t('admin.users.online'), value: 'online' },
  { label: t('admin.users.offline'), value: 'offline' },
])

const accountStatusOptions = computed(() => [
  { label: t('admin.users.accountStatus.active'), value: 'active' },
  { label: t('admin.users.accountStatus.banned'), value: 'banned' },
])

async function fetchApplications() {
  try {
    const data = await api.get<{ applications: Application[] }>('/dev/applications')
    applications.value = data?.applications || []
  }
  catch (error) {
    console.error('获取应用列表失败:', error)
  }
}

async function fetchUsers() {
  loading.value = true
  try {
    const data = await api.get<{ users: User[] }>('/dev/app-users')
    users.value = Array.isArray(data?.users) ? data.users : []
  }
  catch (error) {
    console.error('获取用户列表失败:', error)
    users.value = []
  }
  finally {
    loading.value = false
  }
}

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

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

function goToUserDevices(user: User) {
  router.push(`/admin/devices?user_id=${user.id}`)
}

async function toggleUserStatus(user: User) {
  const newStatus = user.status === 'banned' ? 'active' : 'banned'
  try {
    await api.post('/dev/app-users/batch/status', {
      user_ids: [Number(user.id)],
      status: newStatus,
    })
    toast.success(t('admin.users.statusUpdateSuccess'))
    fetchUsers()
  }
  catch (error: any) {
    console.error('切换用户状态失败:', error)
    toast.error(error.message || t('admin.users.statusUpdateFailed'))
  }
}

function confirmDeleteUser(user: User) {
  deleteTarget.value = user
  deleteDialogOpen.value = true
}

async function handleDeleteUser() {
  if (!deleteTarget.value)
    return

  try {
    await api.delete(`/dev/app-users/${deleteTarget.value.id}`)
    toast.success(t('admin.users.deleteSuccess'))
    fetchUsers()
  }
  catch (error: any) {
    console.error('删除用户失败:', error)
    toast.error(error.message || t('admin.users.deleteFailed'))
  }
  finally {
    deleteTarget.value = null
  }
}

function confirmBatchDelete(ids: (string | number)[]) {
  batchDeleteIds.value = ids
  batchDeleteDialogOpen.value = true
}

async function handleBatchDelete() {
  try {
    await api.delete('/dev/app-users/batch', { user_ids: batchDeleteIds.value.map(id => Number(id)) } as any)
    toast.success(t('admin.users.deleteSuccess'))
    fetchUsers()
  }
  catch (error: any) {
    console.error('批量删除失败:', error)
    toast.error(error.message || t('admin.users.deleteFailed'))
  }
  finally {
    batchDeleteIds.value = []
  }
}

async function batchToggleStatus(ids: (string | number)[], status: string) {
  try {
    await api.post('/dev/app-users/batch/status', { user_ids: ids.map(id => Number(id)), status })
    toast.success(t('admin.users.batchUpdateSuccess'))
    fetchUsers()
  }
  catch (error: any) {
    console.error('批量更新状态失败:', error)
    toast.error(error.message || t('admin.users.batchUpdateFailed'))
  }
}

onMounted(() => {
  fetchApplications()
  fetchUsers()
})

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

<template>
  <BasicPage
    :title="t('admin.users.title')"
    :description="t('admin.users.description')"
    sticky
  >
    <template #actions>
      <UiButton @click="goToCreate">
        <Plus class="mr-2 h-4 w-4" />
        {{ t('admin.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('admin.users.totalUsers') }}
            </UiCardTitle>
            <Users class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ filteredUsers.length }}
            </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('admin.users.online') }}
            </UiCardTitle>
            <CheckCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ onlineCount }}
            </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('admin.users.offline') }}
            </UiCardTitle>
            <Clock class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ offlineCount }}
            </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('admin.users.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">
          <DataTable
            ref="tableRef"
            :loading
            :data="filteredUsers"
            :on-edit="goToEdit"
            :on-toggle-status="toggleUserStatus"
            :on-delete="confirmDeleteUser"
            :on-manage-devices="goToUserDevices"
            @refresh="fetchUsers"
            @batch-unban="batchToggleStatus(tableRef?.table?.getSelectedRowModel().rows.filter((r: any) => r.original.status === 'banned').map((r: any) => r.original.id) || [], 'active')"
            @batch-ban="batchToggleStatus(tableRef?.table?.getSelectedRowModel().rows.filter((r: any) => r.original.status !== 'banned').map((r: any) => r.original.id) || [], 'banned')"
            @batch-delete="confirmBatchDelete(tableRef?.table?.getSelectedRowModel().rows.map((r: any) => r.original.id) || [])"
          >
            <template #filters>
              <SingleFilter
                v-model="appFilter"
                :title="t('admin.users.application')"
                :options="applicationOptions"
              />
              <SingleFilter
                v-model="statusFilter"
                :title="t('admin.users.onlineStatus')"
                :options="statusOptions"
              />
              <SingleFilter
                v-model="accountStatusFilter"
                :title="t('admin.users.accountStatus.title')"
                :options="accountStatusOptions"
              />
              <DateRangeFilter
                v-model:start-model-value="lastLoginStartDate"
                v-model:end-model-value="lastLoginEndDate"
                :title="t('admin.users.lastLoginTime')"
              />
              <DateRangeFilter
                v-model:start-model-value="createdStartDate"
                v-model:end-model-value="createdEndDate"
                :title="t('admin.users.registerTime')"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="deleteDialogOpen"
      destructive
      :confirm-button-text="t('admin.users.delete')"
      :cancel-button-text="t('common.cancel')"
      @confirm="handleDeleteUser"
    >
      <template #title>
        {{ t('admin.users.deleteUser') }}
      </template>
      <template #description>
        {{ t('admin.users.deleteConfirm', { username: deleteTarget?.username }) }}
      </template>
    </ConfirmDialog>

    <ConfirmDialog
      v-model:open="batchDeleteDialogOpen"
      destructive
      :confirm-button-text="t('admin.users.delete')"
      :cancel-button-text="t('common.cancel')"
      @confirm="handleBatchDelete"
    >
      <template #title>
        {{ t('admin.users.batchDeleteUsers') }}
      </template>
      <template #description>
        {{ t('admin.users.batchDeleteConfirm', { count: batchDeleteIds.length }) }}
      </template>
    </ConfirmDialog>
  </BasicPage>
</template>
