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

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

import type { Card } from '@/pages/admin/cards/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 getColumns(actions: {
  onToggleStatus: (row: Card) => void
  onDelete: (row: Card) => void
}, t: Composer['t']): ColumnDef<Card>[] {
  return [
    {
      accessorKey: 'card_key',
      header: () => t('admin.cards.columns.cardKey'),
      cell: ({ row }) => {
        const cardKey = row.getValue('card_key') as string
        if (!cardKey)
          return '-'
        return h('div', { class: 'flex items-center space-x-2' }, [
          h('code', { class: 'text-xs bg-muted px-2 py-1 rounded font-mono' }, cardKey),
          h(Copy, { class: 'h-4 w-4', size: 'sm', content: cardKey }),
        ])
      },
    },
    {
      accessorKey: 'application.name',
      header: () => t('admin.cards.columns.application'),
      cell: ({ row }) => {
        const appName = row.original.application?.name
        return appName ? h(Badge, { variant: 'secondary' }, () => appName) : '-'
      },
    },
    {
      accessorKey: 'card_type.name',
      header: () => t('admin.cards.columns.type'),
      cell: ({ row }) => {
        const typeName = row.original.card_type?.name
        return typeName ? h(Badge, { variant: 'outline' }, () => typeName) : '-'
      },
    },
    {
      accessorKey: 'card_type.price',
      header: () => t('admin.cards.columns.faceValue'),
      cell: ({ row }) => {
        const price = row.original.card_type?.price
        return price != null ? `¥${price}` : '-'
      },
    },
    {
      accessorKey: 'card_type.value',
      header: () => t('admin.cards.columns.duration'),
      cell: ({ row }) => {
        const value = row.original.card_type?.value
        const billingType = row.original.card_type?.billing_type
        if (value == null)
          return '-'
        if (value === -1)
          return t('admin.cards.columns.permanent')
        if (billingType === 'subscription')
          return `${value}${t('admin.cards.columns.hours')}`
        if (billingType === 'timer')
          return `${value}${t('admin.cards.columns.minutes')}`
        if (billingType === 'points')
          return `${value}${t('admin.cards.columns.points')}`
        return String(value)
      },
    },
    {
      accessorKey: 'status',
      header: () => t('admin.cards.columns.status'),
      cell: ({ row }) => {
        const status = row.getValue('status') as string
        if (!status || status === '') {
          return h(Badge, { variant: 'default' }, () => t('admin.cards.unused'))
        }
        const statusMap: Record<string, { text: string, variant: any }> = {
          unused: { text: t('admin.cards.unused'), variant: 'default' },
          used: { text: t('admin.cards.used'), variant: 'secondary' },
          banned: { text: t('admin.cards.banned'), variant: 'destructive' },
        }
        const { text, variant } = statusMap[status] || { text: status, variant: 'default' }
        return h(Badge, { variant }, () => text)
      },
    },
    {
      accessorKey: 'app_user.username',
      header: () => t('admin.cards.columns.usedUser'),
      cell: ({ row }) => {
        const username = row.original.app_user?.username
        return username || '-'
      },
    },
    {
      accessorKey: 'used_at',
      header: () => t('admin.cards.columns.usedTime'),
      cell: ({ row }) => {
        const usedAt = row.getValue('used_at')
        if (!usedAt)
          return '-'
        try {
          const date = new Date(usedAt 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 '-'
        }
      },
    },
    {
      accessorKey: 'creator.username',
      header: () => t('admin.cards.columns.creator'),
      cell: ({ row }) => {
        const username = row.original.creator?.username
        return username || '-'
      },
    },
    {
      accessorKey: 'created_at',
      header: () => t('admin.cards.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 card = row.original
        const isBanned = card.status === 'banned'

        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.onToggleStatus(card) }, () => [
                    h(Ban, { class: 'mr-2 h-4 w-4' }),
                    isBanned ? t('admin.cards.enable') : t('admin.cards.disable'),
                  ]),
                  h(DropdownMenuSeparator),
                  h(DropdownMenuItem, { class: 'text-destructive', onClick: () => actions.onDelete(card) }, () => [
                    h(Trash2, { class: 'mr-2 h-4 w-4' }),
                    t('admin.cards.delete'),
                  ]),
                ],
              ),
            ],
          },
        )
      },
      enableSorting: false,
      enableHiding: false,
    },
  ]
}
