<script setup lang="ts">
import { Ban, CheckCircle, Layers, Monitor } from 'lucide-vue-next'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
import { toast } from 'vue-sonner'

import type { Device } from '@/pages/admin/devices/data/schema'

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

const { t } = useI18n()
const route = useRoute()

interface Application {
  id: number
  name: string
}

interface User {
  id: number
  username: string
}

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

const appFilter = ref<string>('')
const statusFilter = ref<string>('')
const userIdFilter = ref<string>('')

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

const filteredDevices = computed(() => {
  let result = devices.value

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

  if (statusFilter.value) {
    result = result.filter(device => device.status === statusFilter.value)
  }

  if (userIdFilter.value) {
    result = result.filter(device => String(device.user_id) === userIdFilter.value)
  }

  return result
})

const totalDevices = computed(() => filteredDevices.value.length)
const onlineSessionCount = computed(() => filteredDevices.value.reduce((sum, d) => sum + (d.online_sessions || 0), 0))
const bannedCount = computed(() => filteredDevices.value.filter(device => device.status === 'banned').length)

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

const userOptions = computed(() => {
  return users.value.map(user => ({
    label: user.username,
    value: String(user.id),
  }))
})

const statusOptions = computed(() => [
  { label: t('admin.devices.normal'), value: 'active' },
  { label: t('admin.devices.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() {
  try {
    const data = await api.get<{ users: User[] }>('/dev/app-users')
    users.value = data?.users || []
  }
  catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

async function fetchDevices() {
  loading.value = true
  try {
    const userId = route.query.user_id as string
    const deviceId = route.query.device_id as string

    let url = '/dev/devices'
    const params: string[] = []
    if (userId) {
      params.push(`user_id=${userId}`)
    }
    if (deviceId) {
      params.push(`device_id=${deviceId}`)
    }
    if (params.length > 0) {
      url += `?${params.join('&')}`
    }

    const data = await api.get<{ devices: Device[] }>(url)
    devices.value = Array.isArray(data?.devices) ? data.devices : []
  }
  catch (error) {
    console.error('获取设备列表失败:', error)
    devices.value = []
  }
  finally {
    loading.value = false
  }
}

async function toggleDeviceStatus(device: Device) {
  const newStatus = device.status === 'banned' ? 'active' : 'banned'
  try {
    await api.put(`/dev/devices/${device.id}/status`, { status: newStatus })
    toast.success(t('admin.devices.statusUpdateSuccess'))
    fetchDevices()
  }
  catch (error: any) {
    console.error('切换设备状态失败:', error)
    toast.error(error.message || t('admin.devices.statusUpdateFailed'))
  }
}

function confirmDeleteDevice(device: Device) {
  deleteTarget.value = device
  deleteDialogOpen.value = true
}

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

  try {
    await api.delete(`/dev/devices/${deleteTarget.value.id}`)
    toast.success(t('admin.devices.unbindSuccess'))
    fetchDevices()
  }
  catch (error: any) {
    console.error('解绑设备失败:', error)
    toast.error(error.message || t('admin.devices.unbindFailed'))
  }
  finally {
    deleteTarget.value = null
  }
}

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

async function handleBatchDelete() {
  try {
    await api.delete('/dev/devices/batch', { device_ids: batchDeleteIds.value.map(id => Number(id)) } as any)
    toast.success(t('admin.devices.batchUnbindSuccess'))
    fetchDevices()
  }
  catch (error: any) {
    console.error('批量解绑失败:', error)
    toast.error(error.message || t('admin.devices.batchUnbindFailed'))
  }
  finally {
    batchDeleteIds.value = []
  }
}

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

function confirmForceOffline(device: Device) {
  forceOfflineTarget.value = device
  forceOfflineDialogOpen.value = true
}

async function handleForceOffline() {
  if (!forceOfflineTarget.value)
    return

  try {
    const data = await api.post<{ count: number }>(`/dev/devices/${forceOfflineTarget.value.id}/force-offline`)
    toast.success(`已强制离线 ${data?.count || 0} 个实例`)
    fetchDevices()
  }
  catch (error: any) {
    console.error('强制离线失败:', error)
    toast.error(error.message || '强制离线失败')
  }
  finally {
    forceOfflineTarget.value = null
  }
}

onMounted(() => {
  const userId = route.query.user_id as string
  if (userId) {
    userIdFilter.value = userId
  }

  fetchApplications()
  fetchUsers()
  fetchDevices()
})
</script>

<template>
  <BasicPage
    :title="t('admin.devices.title')"
    :description="t('admin.devices.description')"
    sticky
  >
    <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.devices.totalDevices') }}
            </UiCardTitle>
            <Monitor class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ totalDevices }}
            </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.devices.onlineSessions') }}
            </UiCardTitle>
            <Layers class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ onlineSessionCount }}
            </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.devices.normalDevices') }}
            </UiCardTitle>
            <CheckCircle class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ totalDevices - bannedCount }}
            </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.devices.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="filteredDevices"
            :on-toggle-status="toggleDeviceStatus"
            :on-delete="confirmDeleteDevice"
            :on-force-offline="confirmForceOffline"
            @refresh="fetchDevices"
            @batch-unbind="confirmBatchDelete(tableRef?.table?.getSelectedRowModel().rows.map((r: any) => r.original.id) || [])"
            @batch-ban="batchToggleStatus(tableRef?.table?.getSelectedRowModel().rows.filter((r: any) => r.original.status !== 'banned').map((r: any) => r.original.id) || [], 'banned')"
            @batch-unban="batchToggleStatus(tableRef?.table?.getSelectedRowModel().rows.filter((r: any) => r.original.status === 'banned').map((r: any) => r.original.id) || [], 'active')"
          >
            <template #filters>
              <SingleFilter
                v-model="appFilter"
                :title="t('admin.devices.application')"
                :options="applicationOptions"
              />
              <SingleFilter
                v-model="userIdFilter"
                :title="t('admin.devices.user')"
                :options="userOptions"
              />
              <SingleFilter
                v-model="statusFilter"
                :title="t('admin.devices.status')"
                :options="statusOptions"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="deleteDialogOpen"
      destructive
      :confirm-button-text="t('admin.devices.unbind')"
      :cancel-button-text="t('common.cancel')"
      @confirm="handleDeleteDevice"
    >
      <template #title>
        {{ t('admin.devices.unbindDevice') }}
      </template>
      <template #description>
        {{ t('admin.devices.unbindConfirm', { deviceId: deleteTarget?.device_id }) }}
      </template>
    </ConfirmDialog>

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

    <ConfirmDialog
      v-model:open="forceOfflineDialogOpen"
      destructive
      confirm-button-text="强制离线"
      :cancel-button-text="t('common.cancel')"
      @confirm="handleForceOffline"
    >
      <template #title>
        强制离线
      </template>
      <template #description>
        确定要将设备 "{{ forceOfflineTarget?.device_id }}" 的所有在线实例强制离线吗？该设备将需要重新登录。
      </template>
    </ConfirmDialog>
  </BasicPage>
</template>
