<script setup lang="ts">
import { Boxes, Monitor, Users, Wifi } 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 { Session } from '@/pages/admin/sessions/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/sessions/components/data-table.vue'
import api from '@/services/api'

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

interface Application {
  id: number
  name: string
}

const loading = ref(true)
const sessions = ref<Session[]>([])
const applications = ref<Application[]>([])

const appFilter = ref<string>('')
const searchFilter = ref<string>('')
const usernameFilter = ref<string>('')

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

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

const usernameOptions = computed(() => {
  const usernames = new Set(sessions.value.filter(s => s.is_online && s.username).map(s => s.username as string))
  return Array.from(usernames).map(username => ({
    label: username,
    value: username,
  }))
})

const filteredSessions = computed(() => {
  let result = sessions.value.filter(s => s.is_online)

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

  if (usernameFilter.value) {
    result = result.filter(session => session.username === usernameFilter.value)
  }

  if (searchFilter.value) {
    const search = searchFilter.value.toLowerCase()
    result = result.filter(session =>
      session.instance_id?.toLowerCase().includes(search)
      || session.device_identifier?.toLowerCase().includes(search)
      || session.username?.toLowerCase().includes(search)
      || session.device_name?.toLowerCase().includes(search),
    )
  }

  return result
})

const totalSessions = computed(() => filteredSessions.value.length)
const onlineApps = computed(() => new Set(filteredSessions.value.map(s => s.application_id)).size)
const onlineDevices = computed(() => new Set(filteredSessions.value.filter(s => s.device_identifier).map(s => s.device_identifier)).size)
const onlineUsers = computed(() => new Set(filteredSessions.value.filter(s => s.username).map(s => s.username)).size)

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

async function fetchSessions() {
  loading.value = true
  try {
    const data = await api.get<{ sessions: Session[] }>('/dev/sessions')
    sessions.value = data?.sessions || []
  }
  catch (error: any) {
    console.error('获取会话列表失败:', error)
    toast.error(error.message || '获取会话列表失败')
  }
  finally {
    loading.value = false
  }
}

function confirmForceOffline(session: Session) {
  forceOfflineTarget.value = session
  forceOfflineDialogOpen.value = true
}

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

  try {
    await api.delete(`/dev/sessions/${forceOfflineTarget.value.id}`)
    toast.success('强制下线成功')
    fetchSessions()
  }
  catch (error: any) {
    console.error('强制下线失败:', error)
    toast.error(error.message || '强制下线失败')
  }
  finally {
    forceOfflineTarget.value = null
  }
}

onMounted(() => {
  const deviceFingerprint = route.query.device_fingerprint as string
  if (deviceFingerprint) {
    searchFilter.value = deviceFingerprint
  }

  fetchApplications()
  fetchSessions()
})
</script>

<template>
  <BasicPage
    title="在线实例"
    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">
              在线实例数
            </UiCardTitle>
            <Wifi class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ totalSessions }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              在线应用数
            </UiCardTitle>
            <Boxes class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ onlineApps }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              在线设备数
            </UiCardTitle>
            <Monitor class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ onlineDevices }}
            </div>
          </UiCardContent>
        </UiCard>

        <UiCard>
          <UiCardHeader class="flex flex-row items-center justify-between pb-2 space-y-0">
            <UiCardTitle class="text-sm font-medium">
              在线用户数
            </UiCardTitle>
            <Users class="size-4 text-muted-foreground" />
          </UiCardHeader>
          <UiCardContent>
            <div class="text-2xl font-bold">
              {{ onlineUsers }}
            </div>
          </UiCardContent>
        </UiCard>
      </div>

      <UiCard>
        <UiCardContent class="p-6">
          <DataTable
            :loading
            :data="filteredSessions"
            :applications="applications"
            :app-filter="appFilter"
            :search-filter="searchFilter"
            :on-force-offline="confirmForceOffline"
            @update:app-filter="appFilter = $event"
            @update:search-filter="searchFilter = $event"
            @refresh="fetchSessions"
          >
            <template #filters>
              <SingleFilter
                v-model="appFilter"
                title="应用"
                :options="applicationOptions"
              />
              <SingleFilter
                v-model="usernameFilter"
                title="用户"
                :options="usernameOptions"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>

    <ConfirmDialog
      v-model:open="forceOfflineDialogOpen"
      destructive
      confirm-button-text="强制下线"
      cancel-button-text="取消"
      @confirm="handleForceOffline"
    >
      <template #title>
        强制下线
      </template>
      <template #description>
        确定要将实例 "{{ forceOfflineTarget?.instance_id }}" 强制下线吗？该设备将需要重新登录。
      </template>
    </ConfirmDialog>
  </BasicPage>
</template>
