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

import { h } from 'vue'
import { useRouter } from 'vue-router'

import type { CombinedItem } from '@/pages/admin/agent-apps/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 getStatusVariant(status: string, hasAuthorization: boolean) {
  if (hasAuthorization) {
    return status === 'active' ? 'default' : 'secondary'
  }
  if (status === 'pending')
    return 'outline'
  if (status === 'approved')
    return 'default'
  return 'destructive'
}

export function getStatusText(status: string, hasAuthorization: boolean) {
  if (hasAuthorization) {
    return status === 'active' ? '已授权' : '已禁用'
  }
  const map: Record<string, string> = {
    pending: '待处理',
    approved: '已通过',
    rejected: '已拒绝',
  }
  return map[status] || status
}

export function getItemTypeText(itemType: string) {
  const map: Record<string, string> = {
    authorization: '授权记录',
    request: '收到的申请',
    my_request: '发出的申请',
  }
  return map[itemType] || itemType
}

export function getColumns(actions: {
  onApprove: (row: CombinedItem) => void
  onReject: (row: CombinedItem) => void
  onRemove: (row: CombinedItem) => void
}): ColumnDef<CombinedItem>[] {
  return [
    {
      accessorKey: 'itemType',
      header: '类型',
      cell: ({ row }) => {
        const itemType = row.getValue('itemType') as string
        const variants: Record<string, 'default' | 'secondary' | 'outline' | 'destructive'> = {
          authorization: 'default',
          request: 'outline',
          my_request: 'secondary',
        }
        return h(Badge, { variant: variants[itemType] || 'default' }, () => getItemTypeText(itemType))
      },
    },
    {
      accessorKey: 'agent_name',
      header: '代理商/管理员',
      cell: ({ row }) => {
        const agentName = row.getValue('agent_name') as string
        const itemType = row.original.itemType
        const label = itemType === 'my_request' ? '管理员' : '代理商'
        return h('div', {}, [
          h('div', { class: 'font-medium' }, agentName || '-'),
          h('div', { class: 'text-xs text-muted-foreground' }, label),
        ])
      },
    },
    {
      accessorKey: 'app_name',
      header: '应用',
      cell: ({ row }) => {
        const appName = row.getValue('app_name') as string
        return appName ? h(Badge, { variant: 'secondary' }, () => appName) : '-'
      },
    },
    {
      accessorKey: 'status',
      header: '状态',
      cell: ({ row }) => {
        const status = row.getValue('status') as string
        const hasAuthorization = row.original.hasAuthorization
        const variant = getStatusVariant(status, hasAuthorization)
        const text = getStatusText(status, hasAuthorization)
        return h(Badge, { variant }, () => text)
      },
    },
    {
      accessorKey: 'discount',
      header: '折扣',
      cell: ({ row }) => {
        const hasAuthorization = row.original.hasAuthorization
        if (!hasAuthorization)
          return '-'
        const discount = row.getValue('discount') as number
        return `${(discount * 10).toFixed(1)}折`
      },
    },
    {
      accessorKey: 'balance',
      header: '余额',
      cell: ({ row }) => {
        const hasAuthorization = row.original.hasAuthorization
        if (!hasAuthorization)
          return '-'
        const balance = row.getValue('balance') as number
        return h('span', { class: 'font-medium' }, `¥${balance.toFixed(2)}`)
      },
    },
    {
      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 item = row.original
        const router = useRouter()

        return h(
          DropdownMenu,
          {},
          {
            default: () => [
              h(DropdownMenuTrigger, { asChild: true }, () =>
                h(Button, { variant: 'ghost', class: 'h-8 w-8 p-0' }, () =>
                  h('span', { class: 'sr-only' }, '打开菜单'))),
              h(
                DropdownMenuContent,
                { align: 'end' },
                () => {
                  const items = []

                  if (item.itemType === 'request' && item.status === 'pending') {
                    items.push(
                      h(DropdownMenuItem, { onClick: () => actions.onApprove(item) }, () => [
                        h('span', { class: 'i-lucide-check mr-2 h-4 w-4' }),
                        '批准',
                      ]),
                      h(DropdownMenuItem, { onClick: () => actions.onReject(item) }, () => [
                        h('span', { class: 'i-lucide-x mr-2 h-4 w-4' }),
                        '拒绝',
                      ]),
                    )
                  }

                  if (item.hasAuthorization) {
                    items.push(
                      h(DropdownMenuItem, { onClick: () => router.push(`/admin/agent-apps/${item.authorizationId}/edit`) }, () => [
                        h('span', { class: 'i-lucide-edit mr-2 h-4 w-4' }),
                        '编辑',
                      ]),
                      h(DropdownMenuItem, { onClick: () => router.push(`/admin/agent-apps/${item.authorizationId}/card-types`) }, () => [
                        h('span', { class: 'i-lucide-key mr-2 h-4 w-4' }),
                        '卡密权限',
                      ]),
                      h(DropdownMenuItem, { onClick: () => router.push(`/admin/agent-apps/${item.authorizationId}/recharge`) }, () => [
                        h('span', { class: 'i-lucide-wallet mr-2 h-4 w-4' }),
                        '充值余额',
                      ]),
                    )
                  }

                  if (item.itemType === 'my_request' && item.status === 'pending') {
                    items.push(
                      h(DropdownMenuSeparator),
                      h(DropdownMenuItem, { class: 'text-destructive', onClick: () => actions.onRemove(item) }, () => [
                        h('span', { class: 'i-lucide-trash-2 mr-2 h-4 w-4' }),
                        '撤回申请',
                      ]),
                    )
                  }
                  else if (item.hasAuthorization) {
                    items.push(
                      h(DropdownMenuSeparator),
                      h(DropdownMenuItem, { class: 'text-destructive', onClick: () => actions.onRemove(item) }, () => [
                        h('span', { class: 'i-lucide-trash-2 mr-2 h-4 w-4' }),
                        '移除授权',
                      ]),
                    )
                  }

                  return items
                },
              ),
            ],
          },
        )
      },
      enableSorting: false,
      enableHiding: false,
    },
  ]
}
