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

import { MoreHorizontal, Pencil, ShieldCheck, ShieldOff, Trash2 } from 'lucide-vue-next'
import { h } from 'vue'

import type { RiskRule } from '@/pages/admin/risk-control/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'

const countries: Record<string, { name: string, flag: string }> = {
  CN: { name: '中国', flag: '🇨🇳' },
  US: { name: '美国', flag: '🇺🇸' },
  JP: { name: '日本', flag: '🇯🇵' },
  KR: { name: '韩国', flag: '🇰🇷' },
  GB: { name: '英国', flag: '🇬🇧' },
  DE: { name: '德国', flag: '🇩🇪' },
  FR: { name: '法国', flag: '🇫🇷' },
  IT: { name: '意大利', flag: '🇮🇹' },
  ES: { name: '西班牙', flag: '🇪🇸' },
  RU: { name: '俄罗斯', flag: '🇷🇺' },
  CA: { name: '加拿大', flag: '🇨🇦' },
  AU: { name: '澳大利亚', flag: '🇦🇺' },
  BR: { name: '巴西', flag: '🇧🇷' },
  IN: { name: '印度', flag: '🇮🇳' },
  MX: { name: '墨西哥', flag: '🇲🇽' },
  NL: { name: '荷兰', flag: '🇳🇱' },
  SG: { name: '新加坡', flag: '🇸🇬' },
  HK: { name: '中国香港', flag: '🇭🇰' },
  TW: { name: '中国台湾', flag: '🇹🇼' },
  TH: { name: '泰国', flag: '🇹🇭' },
  VN: { name: '越南', flag: '🇻🇳' },
  MY: { name: '马来西亚', flag: '🇲🇾' },
  ID: { name: '印度尼西亚', flag: '🇮🇩' },
  PH: { name: '菲律宾', flag: '🇵🇭' },
  AE: { name: '阿联酋', flag: '🇦🇪' },
  SA: { name: '沙特阿拉伯', flag: '🇸🇦' },
  TR: { name: '土耳其', flag: '🇹🇷' },
  PL: { name: '波兰', flag: '🇵🇱' },
  SE: { name: '瑞典', flag: '🇸🇪' },
  CH: { name: '瑞士', flag: '🇨🇭' },
  AT: { name: '奥地利', flag: '🇦🇹' },
  BE: { name: '比利时', flag: '🇧🇪' },
  DK: { name: '丹麦', flag: '🇩🇰' },
  FI: { name: '芬兰', flag: '🇫🇮' },
  NO: { name: '挪威', flag: '🇳🇴' },
  IE: { name: '爱尔兰', flag: '🇮🇪' },
  PT: { name: '葡萄牙', flag: '🇵🇹' },
  CZ: { name: '捷克', flag: '🇨🇿' },
  RO: { name: '罗马尼亚', flag: '🇷🇴' },
  HU: { name: '匈牙利', flag: '🇭🇺' },
  IL: { name: '以色列', flag: '🇮🇱' },
  ZA: { name: '南非', flag: '🇿🇦' },
  EG: { name: '埃及', flag: '🇪🇬' },
  NG: { name: '尼日利亚', flag: '🇳🇬' },
  AR: { name: '阿根廷', flag: '🇦🇷' },
  CL: { name: '智利', flag: '🇨🇱' },
  CO: { name: '哥伦比亚', flag: '🇨🇴' },
  PE: { name: '秘鲁', flag: '🇵🇪' },
  NZ: { name: '新西兰', flag: '🇳🇿' },
}

function getCountryDisplay(code: string) {
  const country = countries[code]
  return country ? `${country.flag} ${country.name}` : code
}

export function getColumns(actions: {
  onToggleStatus: (row: RiskRule) => void
  onEdit: (row: RiskRule) => void
  onDelete: (row: RiskRule) => void
}): ColumnDef<RiskRule>[] {
  return [
    {
      accessorKey: 'type',
      header: '类型',
      cell: ({ row }) => {
        const type = row.getValue('type') as string
        const typeMap: Record<string, { text: string, variant: 'default' | 'secondary' | 'outline' | 'destructive' }> = {
          ip: { text: 'IP封禁', variant: 'default' },
          device: { text: '设备封禁', variant: 'secondary' },
          user: { text: '用户封禁', variant: 'outline' },
          region: { text: '地区封禁', variant: 'destructive' },
        }
        const { text, variant } = typeMap[type] || { text: type, variant: 'default' }
        return h(Badge, { variant }, () => text)
      },
    },
    {
      accessorKey: 'value',
      header: '封禁值',
      cell: ({ row }) => {
        const value = row.getValue('value') as string
        const type = row.getValue('type') as string
        if (!value)
          return '-'

        const displayValue = type === 'region' ? getCountryDisplay(value) : value

        return h('div', { class: 'flex items-center space-x-2' }, [
          h('code', { class: 'text-xs bg-muted px-2 py-1 rounded font-mono' }, displayValue),
          h(Copy, { class: 'h-4 w-4', size: 'sm', content: value }),
        ])
      },
    },
    {
      accessorKey: 'reason',
      header: '原因',
      cell: ({ row }) => {
        const reason = row.getValue('reason') as string
        return reason || '-'
      },
    },
    {
      accessorKey: 'status',
      header: '状态',
      cell: ({ row }) => {
        const status = row.getValue('status') as string
        const statusMap: Record<string, { text: string, variant: 'default' | 'secondary' }> = {
          active: { text: '生效中', variant: 'default' },
          inactive: { text: '已失效', variant: 'secondary' },
        }
        const { text, variant } = statusMap[status] || { text: status, variant: 'secondary' }
        return h(Badge, { variant }, () => text)
      },
    },
    {
      accessorKey: 'expires_at',
      header: '过期时间',
      cell: ({ row }) => {
        const expiresAt = row.getValue('expires_at')
        if (!expiresAt)
          return '永久'
        try {
          const date = new Date(expiresAt 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: '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 rule = row.original
        const isActive = rule.status === 'active'

        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' },
                () => [
                  h(DropdownMenuItem, { onClick: () => actions.onToggleStatus(rule) }, () => [
                    isActive ? h(ShieldOff, { class: 'mr-2 h-4 w-4' }) : h(ShieldCheck, { class: 'mr-2 h-4 w-4' }),
                    isActive ? '禁用' : '启用',
                  ]),
                  h(DropdownMenuItem, { onClick: () => actions.onEdit(rule) }, () => [
                    h(Pencil, { class: 'mr-2 h-4 w-4' }),
                    '编辑',
                  ]),
                  h(DropdownMenuSeparator),
                  h(DropdownMenuItem, { class: 'text-destructive', onClick: () => actions.onDelete(rule) }, () => [
                    h(Trash2, { class: 'mr-2 h-4 w-4' }),
                    '删除',
                  ]),
                ],
              ),
            ],
          },
        )
      },
      enableSorting: false,
      enableHiding: false,
    },
  ]
}
