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

import Badge from '@/components/ui/badge/Badge.vue'

import type { Log } from '@/pages/admin/logs/data/schema'

function translateDetails(t: Composer['t'], details: string): string {
  if (!details) return '-'

  const patterns: Array<{
    pattern: RegExp
    template: string
    extract: (match: RegExpMatchArray) => Record<string, string>
  }> = [
    {
      pattern: /^用户注册: (.+)$/,
      template: 'admin.logs.details.register',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^注册失败: 用户已存在 - (.+)$/,
      template: 'admin.logs.details.register_failed_exists',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^用户登录: (.+)$/,
      template: 'admin.logs.details.login',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^登录失败: 用户不存在 - (.+)$/,
      template: 'admin.logs.details.login_failed_not_found',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^登录失败: 密码错误 - (.+)$/,
      template: 'admin.logs.details.login_failed_password',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^登录失败: 余额不足 - (.+)$/,
      template: 'admin.logs.details.login_failed_balance',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^登录失败: 设备绑定数量已达上限 - (.+)$/,
      template: 'admin.logs.details.login_failed_device_limit',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^登录失败: 多开数量已达上限 - (.+)$/,
      template: 'admin.logs.details.login_failed_multi_limit',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^用户充值: (.+), 卡密: (.+), 金额: ([\d.]+)$/,
      template: 'admin.logs.details.recharge',
      extract: (m) => ({ username: m[1], card: m[2], amount: m[3] }),
    },
    {
      pattern: /^充值失败: 用户不存在 - (.+)$/,
      template: 'admin.logs.details.recharge_failed_user_not_found',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^充值失败: 用户已是永久会员 - (.+)$/,
      template: 'admin.logs.details.recharge_failed_permanent',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^充值失败: 卡密不存在 - (.+)$/,
      template: 'admin.logs.details.recharge_failed_card_not_found',
      extract: (m) => ({ card: m[1] }),
    },
    {
      pattern: /^充值失败: 卡密已使用 - (.+)$/,
      template: 'admin.logs.details.recharge_failed_card_used',
      extract: (m) => ({ card: m[1] }),
    },
    {
      pattern: /^用户解绑设备: (.+)$/,
      template: 'admin.logs.details.unbind_device',
      extract: (m) => ({ device: m[1] }),
    },
    {
      pattern: /^扩展API充值: 用户(.+), 类型:(.+), 数量:(\d+)$/,
      template: 'admin.logs.details.extension_recharge',
      extract: (m) => ({ username: m[1], type: m[2], amount: m[3] }),
    },
    {
      pattern: /^扩展API充值失败: 用户不存在 - (.+)$/,
      template: 'admin.logs.details.extension_recharge_failed_user_not_found',
      extract: (m) => ({ userId: m[1] }),
    },
    {
      pattern: /^扩展API充值失败: 用户已是永久会员 - (.+)$/,
      template: 'admin.logs.details.extension_recharge_failed_permanent',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^扩展API充值失败: 类型无效 - (.+)$/,
      template: 'admin.logs.details.extension_recharge_failed_type',
      extract: (m) => ({ type: m[1] }),
    },
    {
      pattern: /^扩展API充值失败: 保存失败 - (.+)$/,
      template: 'admin.logs.details.extension_recharge_failed_save',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^扩展API扣费: 用户(.+), 类型:(.+), 数量:(\d+)$/,
      template: 'admin.logs.details.extension_deduct',
      extract: (m) => ({ username: m[1], type: m[2], amount: m[3] }),
    },
    {
      pattern: /^扩展API扣费失败: 用户不存在 - (.+)$/,
      template: 'admin.logs.details.extension_deduct_failed_user_not_found',
      extract: (m) => ({ userId: m[1] }),
    },
    {
      pattern: /^扩展API扣费失败: 用户已是永久会员 - (.+)$/,
      template: 'admin.logs.details.extension_deduct_failed_permanent',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^扩展API扣费失败: 用户订阅已过期 - (.+)$/,
      template: 'admin.logs.details.extension_deduct_failed_expired',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^扩展API扣费失败: 余额不足 - (.+)$/,
      template: 'admin.logs.details.extension_deduct_failed_balance',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^扩展API扣费失败: 类型无效 - (.+)$/,
      template: 'admin.logs.details.extension_deduct_failed_type',
      extract: (m) => ({ type: m[1] }),
    },
    {
      pattern: /^扩展API扣费失败: 保存失败 - (.+)$/,
      template: 'admin.logs.details.extension_deduct_failed_save',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^创建应用: (.+)$/,
      template: 'admin.logs.details.create_application',
      extract: (m) => ({ name: m[1] }),
    },
    {
      pattern: /^更新应用: (.+)$/,
      template: 'admin.logs.details.update_application',
      extract: (m) => ({ name: m[1] }),
    },
    {
      pattern: /^删除应用: (.+)$/,
      template: 'admin.logs.details.delete_application',
      extract: (m) => ({ name: m[1] }),
    },
    {
      pattern: /^创建用户: (.+) \(应用: (.+)\)$/,
      template: 'admin.logs.details.create_user',
      extract: (m) => ({ username: m[1], app: m[2] }),
    },
    {
      pattern: /^更新用户: (.+)$/,
      template: 'admin.logs.details.update_user',
      extract: (m) => ({ username: m[1] }),
    },
    {
      pattern: /^删除用户: (.+) \(应用: (.+)\)$/,
      template: 'admin.logs.details.delete_user',
      extract: (m) => ({ username: m[1], app: m[2] }),
    },
    {
      pattern: /^解绑设备: (.+) \(应用: (.+)\)$/,
      template: 'admin.logs.details.unbind_device_app',
      extract: (m) => ({ device: m[1], app: m[2] }),
    },
    {
      pattern: /^批量解绑设备: (\d+)个$/,
      template: 'admin.logs.details.batch_unbind',
      extract: (m) => ({ count: m[1] }),
    },
    {
      pattern: /^创建工单: (.+)$/,
      template: 'admin.logs.details.create_ticket',
      extract: (m) => ({ title: m[1] }),
    },
    {
      pattern: /^删除工单: (.+)$/,
      template: 'admin.logs.details.delete_ticket',
      extract: (m) => ({ title: m[1] }),
    },
    {
      pattern: /^创建Webhook: (.+)$/,
      template: 'admin.logs.details.create_webhook',
      extract: (m) => ({ name: m[1] }),
    },
    {
      pattern: /^删除Webhook: (.+)$/,
      template: 'admin.logs.details.delete_webhook',
      extract: (m) => ({ name: m[1] }),
    },
    {
      pattern: /^创建云端常量: (.+)$/,
      template: 'admin.logs.details.create_cloud_constant',
      extract: (m) => ({ key: m[1] }),
    },
    {
      pattern: /^更新云端常量: (.+)$/,
      template: 'admin.logs.details.update_cloud_constant',
      extract: (m) => ({ key: m[1] }),
    },
    {
      pattern: /^删除云端常量: (.+)$/,
      template: 'admin.logs.details.delete_cloud_constant',
      extract: (m) => ({ key: m[1] }),
    },
    {
      pattern: /^创建卡密类型: (.+)$/,
      template: 'admin.logs.details.create_card_type',
      extract: (m) => ({ name: m[1] }),
    },
    {
      pattern: /^更新卡密类型: (.+)$/,
      template: 'admin.logs.details.update_card_type',
      extract: (m) => ({ name: m[1] }),
    },
    {
      pattern: /^删除卡密类型: (.+)$/,
      template: 'admin.logs.details.delete_card_type',
      extract: (m) => ({ name: m[1] }),
    },
  ]

  for (const { pattern, template, extract } of patterns) {
    const match = details.match(pattern)
    if (match) {
      const params = extract(match)
      return t(template, params)
    }
  }

  return details
}

export function getColumns(t: Composer['t']): ColumnDef<Log>[] {
  return [
    {
      accessorKey: 'log_type',
      header: () => t('admin.logs.columns.type'),
      cell: ({ row }) => {
        const type = row.getValue('log_type') as string
        const typeMap: Record<string, { text: string, variant: any }> = {
          operation: { text: t('admin.logs.types.operation'), variant: 'default' },
          verification: { text: t('admin.logs.types.verification'), variant: 'secondary' },
          exception: { text: t('admin.logs.types.exception'), variant: 'destructive' },
        }
        const { text, variant } = typeMap[type] || { text: type, variant: 'default' }
        return h(Badge, { variant }, () => text)
      },
    },
    {
      accessorKey: 'action',
      header: () => t('admin.logs.columns.action'),
      cell: ({ row }) => {
        const action = row.getValue('action') as string
        if (!action) return '-'
        const actionKey = `admin.logs.actions.${action}`
        const translated = t(actionKey)
        return translated === actionKey ? action : translated
      },
    },
    {
      accessorKey: 'details',
      header: () => t('admin.logs.columns.detail'),
      cell: ({ row }) => {
        const details = row.getValue('details') as string
        if (!details) return '-'
        const translated = translateDetails(t, details)
        return h('div', { class: 'max-w-xs truncate', title: details }, translated)
      },
    },
    {
      accessorKey: 'status',
      header: () => t('admin.logs.columns.status'),
      cell: ({ row }) => {
        const status = row.getValue('status') as string
        const statusMap: Record<string, { text: string, variant: any }> = {
          success: { text: t('admin.success'), variant: 'default' },
          failed: { text: t('admin.failed'), variant: 'destructive' },
        }
        const { text, variant } = statusMap[status] || { text: status, variant: 'default' }
        return h(Badge, { variant }, () => text)
      },
    },
    {
      accessorKey: 'ip_address',
      header: () => t('admin.logs.columns.ip'),
      cell: ({ row }) => {
        const ip = row.getValue('ip_address') as string
        return h('code', { class: 'text-xs font-mono' }, ip || '-')
      },
    },
    {
      accessorKey: 'application.name',
      header: () => t('admin.logs.columns.application'),
      cell: ({ row }) => {
        const appName = row.original.application?.name
        return appName ? h(Badge, { variant: 'outline' }, () => appName) : '-'
      },
    },
    {
      accessorKey: 'user.username',
      header: () => t('admin.logs.columns.user'),
      cell: ({ row }) => {
        const username = row.original.user?.username || row.original.app_user?.username
        return username || '-'
      },
    },
    {
      accessorKey: 'created_at',
      header: () => t('admin.logs.columns.time'),
      cell: ({ row }) => {
        const createdAt = row.getValue('created_at')
        if (!createdAt) return '-'
        try {
          const date = new Date(createdAt as string)
          if (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 '-'
        }
      },
    },
  ]
}
