import type { ColumnDef } from '@tanstack/vue-table'

import { Ban, Eye, LogOut, MoreHorizontal, Trash2 } from 'lucide-vue-next'
import { h } from 'vue'
import { useRouter } from 'vue-router'

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

import Badge from '@/components/ui/badge/Badge.vue'
import Button from '@/components/ui/button/Button.vue'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'

export function getColumns(actions: {
  onToggleStatus: (row: Device) => void
  onDelete: (row: Device) => void
  onForceOffline: (row: Device) => void
}): ColumnDef<Device>[] {
  const router = useRouter()

  return [
    {
      accessorKey: 'device_id',
      header: '设备指纹',
      cell: ({ row }) => {
        const deviceId = row.getValue('device_id') as string
        if (!deviceId)
          return '-'
        const displayText = deviceId.length > 16
          ? `${deviceId.substring(0, 8)}...${deviceId.substring(deviceId.length - 4)}`
          : deviceId
        return h('span', { class: 'font-mono text-xs' }, displayText)
      },
    },
    {
      accessorKey: 'device_name',
      header: '设备名称',
      cell: ({ row }) => {
        const deviceName = row.getValue('device_name') as string
        return deviceName || '-'
      },
    },
    {
      accessorKey: 'device_type',
      header: '设备类型',
      cell: ({ row }) => {
        const deviceType = row.getValue('device_type') as string
        return deviceType || '-'
      },
    },
    {
      accessorKey: 'user.username',
      header: '所属用户',
      cell: ({ row }) => {
        const username = row.original.user?.username
        return username || '-'
      },
    },
    {
      accessorKey: 'application.name',
      header: '所属应用',
      cell: ({ row }) => {
        const appName = row.original.application?.name
        return appName ? h(Badge, { variant: 'secondary' }, () => appName) : '-'
      },
    },
    {
      id: 'online_status',
      header: '在线状态',
      cell: ({ row }) => {
        const onlineSessions = row.original.online_sessions || 0
        const isOnline = onlineSessions > 0
        return h(Badge, { variant: isOnline ? 'default' : 'secondary' }, () => isOnline ? '在线' : '离线')
      },
    },
    {
      accessorKey: 'online_sessions',
      header: '在线实例',
      cell: ({ row }) => {
        const onlineSessions = row.getValue('online_sessions') as number
        const count = onlineSessions || 0
        if (count === 0) {
          return h('span', { class: 'text-muted-foreground' }, '0')
        }
        return h(Badge, { variant: 'default', class: 'cursor-pointer' }, () => `${count} 个`)
      },
    },
    {
      accessorKey: 'status',
      header: '状态',
      cell: ({ row }) => {
        const status = (row.getValue('status') as string) || 'active'
        const isBanned = status === 'banned'
        return h(Badge, { variant: isBanned ? 'destructive' : 'default' }, () => isBanned ? '已禁用' : '正常')
      },
    },
    {
      accessorKey: 'created_at',
      header: '绑定时间',
      cell: ({ row }) => {
        const createdAt = row.getValue('created_at')
        if (!createdAt)
          return '-'
        try {
          const date = new Date(createdAt as string)
          if (Number.isNaN(date.getTime()))
            return '-'
          return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
          })
        }
        catch {
          return '-'
        }
      },
    },
    {
      id: 'actions',
      header: () => h('span', { class: 'sr-only' }, '操作'),
      cell: ({ row }) => {
        const device = row.original
        const isBanned = device.status === 'banned'
        const hasOnlineSessions = (device.online_sessions || 0) > 0

        return h(
          DropdownMenu,
          {},
          {
            default: () => [
              h(DropdownMenuTrigger, { asChild: true }, () =>
                h(Button, { variant: 'ghost', class: 'h-8 w-8 p-0' }, () => [
                  h(MoreHorizontal, { class: 'h-4 w-4' }),
                  h('span', { class: 'sr-only' }, '打开菜单'),
                ])),
              h(
                DropdownMenuContent,
                { align: 'end' },
                () => [
                  hasOnlineSessions
                    ? h(DropdownMenuItem, { onClick: () => router.push(`/admin/sessions?device_fingerprint=${device.device_id}`) }, () => [
                        h(Eye, { class: 'mr-2 h-4 w-4' }),
                        '查看实例',
                      ])
                    : null,
                  hasOnlineSessions
                    ? h(DropdownMenuItem, { class: 'text-destructive', onClick: () => actions.onForceOffline(device) }, () => [
                        h(LogOut, { class: 'mr-2 h-4 w-4' }),
                        '强制离线',
                      ])
                    : null,
                  h(DropdownMenuItem, { onClick: () => actions.onToggleStatus(device) }, () => [
                    h(Ban, { class: 'mr-2 h-4 w-4' }),
                    isBanned ? '启用' : '禁用',
                  ]),
                  h(DropdownMenuSeparator),
                  h(DropdownMenuItem, { class: 'text-destructive', onClick: () => actions.onDelete(device) }, () => [
                    h(Trash2, { class: 'mr-2 h-4 w-4' }),
                    '解绑',
                  ]),
                ].filter(Boolean),
              ),
            ],
          },
        )
      },
      enableSorting: false,
      enableHiding: false,
    },
  ]
}
