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

import { Download, File, MoreHorizontal, Pencil, Power, PowerOff, Trash2 } from 'lucide-vue-next'
import { h } from 'vue'

import type { CloudConstant } from '@/pages/admin/cloud-constants/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,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'

export function getColumns(actions: {
  onEdit: (row: CloudConstant) => void
  onDelete: (row: CloudConstant) => void
  onToggleStatus: (row: CloudConstant) => void
  onDownload: (row: CloudConstant) => void
}, t: Composer['t']): ColumnDef<CloudConstant>[] {
  return [
    {
      accessorKey: 'key',
      header: () => t('admin.cloudConstants.columns.key'),
      cell: ({ row }) => {
        const key = row.getValue('key') as string
        if (!key)
          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' }, key),
          h(Copy, { class: 'h-4 w-4', size: 'sm', content: key }),
        ])
      },
    },
    {
      accessorKey: 'value',
      header: () => t('admin.cloudConstants.columns.value'),
      cell: ({ row }) => {
        const value = row.getValue('value') as string
        const varType = row.original.var_type
        if (!value)
          return '-'
        if (varType === 'binary') {
          const originalName = row.original.original_name || value
          return h('div', { class: 'flex items-center gap-2' }, [
            h(File, { class: 'h-4 w-4 text-muted-foreground' }),
            h('span', { class: 'max-w-xs truncate', title: originalName }, originalName),
          ])
        }
        return h('div', { class: 'max-w-xs truncate', title: value }, value)
      },
    },
    {
      accessorKey: 'var_type',
      header: () => t('admin.cloudConstants.columns.type'),
      cell: ({ row }) => {
        const type = row.getValue('var_type') as string
        const typeMap: Record<string, string> = {
          integer: t('admin.cloudConstants.types.integer'),
          decimal: t('admin.cloudConstants.types.decimal'),
          string: t('admin.cloudConstants.types.string'),
          binary: t('admin.cloudConstants.types.binary'),
        }
        return h(Badge, { variant: 'secondary' }, () => typeMap[type || 'string'] || type || 'string')
      },
    },
    {
      accessorKey: 'description',
      header: () => t('admin.cloudConstants.columns.description'),
      cell: ({ row }) => {
        const description = row.getValue('description') as string
        if (!description)
          return '-'
        return h('div', { class: 'max-w-xs truncate', title: description }, description)
      },
    },
    {
      accessorKey: 'application_name',
      header: () => t('admin.cloudConstants.columns.application'),
      cell: ({ row }) => {
        const appName = row.getValue('application_name') as string
        const appId = row.original.app_id
        if (!appId)
          return h(Badge, { variant: 'outline' }, () => t('admin.cloudConstants.notLinked'))
        if (!appName)
          return '-'
        return h(Badge, { variant: 'outline' }, () => appName)
      },
    },
    {
      accessorKey: 'status',
      header: () => t('admin.cloudConstants.columns.status'),
      cell: ({ row }) => {
        const status = row.getValue('status') as string
        const isActive = status === 'active'
        return h(Badge, { variant: isActive ? 'default' : 'destructive' }, () => isActive ? t('admin.cloudConstants.statusActive') : t('admin.cloudConstants.statusInactive'))
      },
    },
    {
      accessorKey: 'created_at',
      header: () => t('admin.cloudConstants.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 constant = row.original

        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' },
                () => {
                  const items = [
                    h(DropdownMenuItem, { onClick: () => actions.onEdit(constant) }, () => [
                      h(Pencil, { class: 'mr-2 h-4 w-4' }),
                      t('admin.cloudConstants.edit'),
                    ]),
                  ]

                  if (constant.var_type === 'binary') {
                    items.push(
                      h(DropdownMenuItem, { onClick: () => actions.onDownload(constant) }, () => [
                        h(Download, { class: 'mr-2 h-4 w-4' }),
                        '下载文件',
                      ]),
                    )
                  }

                  items.push(
                    h(DropdownMenuItem, { onClick: () => actions.onToggleStatus(constant) }, () => [
                      constant.status === 'active' ? h(PowerOff, { class: 'mr-2 h-4 w-4' }) : h(Power, { class: 'mr-2 h-4 w-4' }),
                      constant.status === 'active' ? t('admin.cloudConstants.disable') : t('admin.cloudConstants.enable'),
                    ]),
                    h(DropdownMenuItem, { class: 'text-destructive', onClick: () => actions.onDelete(constant) }, () => [
                      h(Trash2, { class: 'mr-2 h-4 w-4' }),
                      t('admin.cloudConstants.delete'),
                    ]),
                  )

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