<script setup lang="ts">
import type { ColumnDef } from '@tanstack/vue-table'

import { computed } from 'vue'

import type { DataTableProps } from '@/components/data-table/types'
import type { Session } from '@/pages/admin/sessions/data/schema'

import DataTable from '@/components/data-table/data-table.vue'
import { generateVueTable } from '@/components/data-table/use-generate-vue-table'
import DataTableViewOptions from '@/components/data-table/view-options.vue'
import { getColumns } from '@/pages/admin/sessions/components/columns'
import DataTableToolbar from '@/pages/admin/sessions/components/data-table-toolbar.vue'

const props = defineProps<Omit<DataTableProps<Session>, 'columns'> & {
  applications: { id: number, name: string }[]
  appFilter?: string
  searchFilter?: string
  onForceOffline: (row: Session) => void
}>()
const emit = defineEmits<{
  'update:appFilter': [value: string]
  'update:searchFilter': [value: string]
  'refresh': []
}>()

const columns = computed<ColumnDef<Session>[]>(() => getColumns({
  onForceOffline: props.onForceOffline,
}))

const table = generateVueTable<Session>({ ...props, columns: columns.value }, columns.value)

const columnLabels: Record<string, string> = {
  instance_id: '实例标识',
  device_identifier: '设备指纹',
  device_name: '设备名称',
  username: '所属用户',
  app_name: '所属应用',
  last_heartbeat: '最后心跳',
  created_at: '创建时间',
}

defineExpose({
  table,
})
</script>

<template>
  <DataTable :columns="columns" :data :loading :table @refresh="emit('refresh')">
    <template #toolbar>
      <div class="space-y-3">
        <div class="flex flex-wrap items-center justify-between gap-2">
          <div class="flex flex-wrap items-center gap-2">
            <DataTableToolbar
              :table
              :search-filter="searchFilter"
              @update:search-filter="emit('update:searchFilter', $event)"
              @refresh="emit('refresh')"
            />
            <slot name="filters" />
          </div>
          <DataTableViewOptions :table="table" :column-labels="columnLabels" />
        </div>
      </div>
    </template>
  </DataTable>
</template>
