<script setup lang="ts">
import { Ban, CheckCircle, Layers, Loader2, Monitor } from 'lucide-vue-next'
import { computed, onMounted, ref, watch } 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
}

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

const appFilter = ref<string>('')
const statusFilter = ref<string>('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const bannedCount = ref(0)

const forceOfflineDialogOpen = ref(false)
const forceOfflineTarget = ref<Device | null>(null)

const totalDevices = computed(() => total.value)
const onlineSessionCount = computed(() => devices.value.reduce((sum, d) => sum + (d.online_sessions || 0), 0))

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

const statusOptions = computed(() => [
  { label: t('agent.devices.normal'), value: 'active' },
  { label: t('agent.devices.banned'), value: 'banned' },
])

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

async function fetchDevices() {
  loading.value = true
  try {
    const params = new URLSearchParams()
    params.append('page', String(currentPage.value))
    params.append('page_size', String(pageSize.value))

    if (appFilter.value) {
      params.append('application_id', appFilter.value)
    }
    if (statusFilter.value) {
      params.append('status', statusFilter.value)
    }

    const data = await api.get<any>(`/agent/devices?${params.toString()}`)
    devices.value = Array.isArray(data?.devices) ? data.devices : []
    total.value = data?.total || 0
    bannedCount.value = data?.banned_count || 0
  }
  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(`/agent/devices/${device.id}/status`, { status: newStatus })
    toast.success(t('agent.devices.statusUpdateSuccess'))
    fetchDevices()
  }
  catch (error: any) {
    console.error('切换设备状态失败:', error)
    toast.error(error.message || t('agent.devices.statusUpdateFailed'))
  }
}

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 }>(`/agent/devices/${forceOfflineTarget.value.id}/force-offline`)
    toast.success(t('agent.devices.forceOfflineSuccess', { count: data?.count || 0 }))
    fetchDevices()
  }
  catch (error: any) {
    console.error('强制离线失败:', error)
    toast.error(error.message || t('agent.devices.forceOfflineFailed'))
  }
  finally {
    forceOfflineTarget.value = null
  }
}

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

watch([currentPage, pageSize], () => {
  fetchDevices()
})

watch([appFilter, statusFilter], () => {
  currentPage.value = 1
  fetchDevices()
})

const serverPagination = computed(() => ({
  page: currentPage.value,
  pageSize: pageSize.value,
  total: total.value,
  onPageChange: (page: number) => {
    currentPage.value = page
  },
  onPageSizeChange: (size: number) => {
    pageSize.value = size
    currentPage.value = 1
  },
}))
</script>

<template>
  <BasicPage
    :title="t('agent.devices.title')"
    :description="t('agent.devices.description')"
    :breadcrumbs="[
      { title: t('nav.dashboard'), href: '/agent' },
      { title: t('nav.devices') },
    ]"
    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('agent.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('agent.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('agent.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('agent.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">
          <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="devices"
            :server-pagination="serverPagination"
            :on-toggle-status="toggleDeviceStatus"
            :on-delete="() => {}"
            :on-force-offline="confirmForceOffline"
            @refresh="fetchDevices"
          >
            <template #filters>
              <SingleFilter
                v-model="appFilter"
                :title="t('agent.devices.application')"
                :options="applicationOptions"
              />
              <SingleFilter
                v-model="statusFilter"
                :title="t('agent.devices.status')"
                :options="statusOptions"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="forceOfflineDialogOpen"
      destructive
      :confirm-button-text="t('agent.devices.forceOffline')"
      :cancel-button-text="t('common.cancel')"
      @confirm="handleForceOffline"
    >
      <template #title>
        {{ t('agent.devices.forceOfflineTitle') }}
      </template>
      <template #description>
        {{ t('agent.devices.forceOfflineConfirm', { deviceId: forceOfflineTarget?.device_id }) }}
      </template>
    </ConfirmDialog>
  </BasicPage>
</template>
