<script setup lang="ts">
import { Boxes, Loader2, Monitor, Users, Wifi } 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 { 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 } = 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 currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

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 filteredSessions = computed(() => {
  return sessions.value.filter(s => s.is_online)
})

const totalSessions = computed(() => total.value)
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)

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

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 fetchSessions() {
  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('app_id', appFilter.value)
    }
    if (searchFilter.value) {
      params.append('search', searchFilter.value)
    }

    const data = await api.get<{ sessions: Session[], total: number }>(`/agent/sessions?${params.toString()}`)
    sessions.value = data?.sessions || []
    total.value = data?.total || 0
  }
  catch (error: any) {
    console.error('获取会话列表失败:', error)
    toast.error(error.message || t('agent.sessions.loadFailed'))
  }
  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(`/agent/sessions/${forceOfflineTarget.value.id}`)
    toast.success(t('agent.sessions.forceOfflineSuccess'))
    fetchSessions()
  }
  catch (error: any) {
    console.error('强制下线失败:', error)
    toast.error(error.message || t('agent.sessions.forceOfflineFailed'))
  }
  finally {
    forceOfflineTarget.value = null
  }
}

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

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

watch([appFilter, searchFilter], () => {
  currentPage.value = 1
  fetchSessions()
})
</script>

<template>
  <BasicPage
    :title="t('agent.sessions.title')"
    :description="t('agent.sessions.description')"
    :breadcrumbs="[
      { title: t('nav.dashboard'), href: '/agent' },
      { title: t('nav.sessions') },
    ]"
    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.sessions.onlineSessions') }}
            </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">
              {{ t('agent.sessions.onlineApps') }}
            </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">
              {{ t('agent.sessions.onlineDevices') }}
            </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">
              {{ t('agent.sessions.onlineUsers') }}
            </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">
          <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
            :loading
            :data="filteredSessions"
            :server-pagination="serverPagination"
            :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="t('agent.sessions.application')"
                :options="applicationOptions"
              />
            </template>
          </DataTable>
        </UiCardContent>
      </UiCard>
    </div>

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