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

import { Ban, MoreHorizontal, RefreshCw, Trash2 } from 'lucide-vue-next'
import { h } from 'vue'

import type { APIKey } from '@/pages/admin/extension/data/schema'

import { Copy } from '@/components/sva-ui/copy'
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 getAPIKeyColumns(actions: {
  onToggleStatus: (row: APIKey) => void
  onRegenerate: (row: APIKey) => void
  onDelete: (row: APIKey) => void
}, t: Composer['t']): ColumnDef<APIKey>[] {
  return [
    {
      accessorKey: 'name',
      header: () => t('admin.extension.apiKeys.columns.name'),
      cell: ({ row }) => {
        const name = row.getValue('name') as string
        return name || '-'
      },
    },
    {
      accessorKey: 'application_name',
      header: () => t('admin.extension.apiKeys.columns.application'),
      cell: ({ row }) => {
        const appName = row.getValue('application_name') as string
        return appName ? h(Badge, { variant: 'secondary' }, () => appName) : '-'
      },
    },
    {
      accessorKey: 'access_key',
      header: () => t('admin.extension.apiKeys.columns.accessKey'),
      cell: ({ row }) => {
        const accessKey = row.getValue('access_key') as string
        return accessKey
          ? h('div', { class: 'flex items-center space-x-2' }, [
              h('code', { class: 'text-xs bg-muted px-2 py-1 rounded font-mono' }, accessKey),
              h(Copy, { class: 'h-4 w-4', size: 'sm', content: accessKey }),
            ])
          : '-'
      },
    },
    {
      accessorKey: 'secret_key',
      header: () => t('admin.extension.apiKeys.columns.secretKey'),
      cell: ({ row }) => {
        const secretKey = row.getValue('secret_key') as string
        return secretKey ? h('code', { class: 'text-xs bg-muted px-2 py-1 rounded font-mono' }, '••••••••••••••••') : '-'
      },
    },
    {
      accessorKey: 'permissions',
      header: () => t('admin.extension.apiKeys.columns.permissions'),
      cell: ({ row }) => {
        const permissions = row.getValue('permissions') as string
        try {
          const permissionList = JSON.parse(permissions || '[]')
          return h('div', { class: 'flex flex-wrap gap-1' }, permissionList.slice(0, 3).map((permission: string) =>
            h(Badge, { variant: 'outline', class: 'text-xs' }, () => permission),
          ))
        }
        catch {
          return '-'
        }
      },
    },
    {
      accessorKey: 'status',
      header: () => t('admin.extension.apiKeys.columns.status'),
      cell: ({ row }) => {
        const status = row.getValue('status') as string
        return h(Badge, { variant: status === 'active' ? 'default' : 'secondary' }, () =>
          status === 'active' ? t('admin.extension.enabled') : t('admin.extension.disabled'))
      },
    },
    {
      accessorKey: 'created_at',
      header: () => t('admin.extension.apiKeys.columns.createdAt'),
      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' }, t('common.actions')),
      cell: ({ row }) => {
        const apiKey = row.original
        const isDisabled = apiKey.status === 'inactive'

        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' }, t('common.openMenu')),
                ])),
              h(
                DropdownMenuContent,
                { align: 'end' },
                () => [
                  h(DropdownMenuItem, { onClick: () => actions.onRegenerate(apiKey) }, () => [
                    h(RefreshCw, { class: 'mr-2 h-4 w-4' }),
                    t('admin.extension.apiKeys.regenerate'),
                  ]),
                  h(DropdownMenuItem, { onClick: () => actions.onToggleStatus(apiKey) }, () => [
                    h(Ban, { class: 'mr-2 h-4 w-4' }),
                    isDisabled ? t('admin.extension.apiKeys.enable') : t('admin.extension.apiKeys.disable'),
                  ]),
                  h(DropdownMenuSeparator),
                  h(DropdownMenuItem, { class: 'text-destructive', onClick: () => actions.onDelete(apiKey) }, () => [
                    h(Trash2, { class: 'mr-2 h-4 w-4' }),
                    t('admin.extension.apiKeys.delete'),
                  ]),
                ],
              ),
            ],
          },
        )
      },
      enableSorting: false,
      enableHiding: false,
    },
  ]
}
