import { Download, Edit, Trash2, Upload, Archive, ArrowDownToLine, Package } from 'lucide-vue-next'
import type { ColumnDef } from '@tanstack/vue-table'

import { h } from 'vue'

import type { Version } from '@/pages/admin/versions/data/schema'

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

interface ColumnOptions {
  onDownload: (row: Version) => void
  onDownloadFullPackage?: (row: Version) => void
  onEdit: (row: Version) => void
  onDelete: (row: Version) => void
  onPublish?: (row: Version) => void
  onDeprecate?: (row: Version) => void
  onRollback?: (row: Version) => void
  onDownloadDelta?: (row: Version) => void
}

function formatFileSize(bytes: number): string {
  if (bytes === 0)
    return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`
}

export function getColumns(options: ColumnOptions, t: (key: string) => string): ColumnDef<Version>[] {
  return [
    {
      accessorKey: 'version',
      header: () => t('admin.versions.columns.version'),
      cell: ({ row }) => {
        return h('code', { class: 'text-sm bg-muted px-2 py-1 rounded' }, row.original.version)
      },
    },
    {
      accessorKey: 'application_name',
      header: () => t('admin.versions.columns.application'),
      cell: ({ row }) => {
        const appName = row.original.application_name
        return appName ? h(Badge, { variant: 'secondary' }, () => appName) : '-'
      },
    },
    {
      accessorKey: 'description',
      header: () => t('admin.versions.columns.description'),
      cell: ({ row }) => {
        return h('div', { class: 'max-w-xs truncate' }, row.original.description || '-')
      },
    },
    {
      accessorKey: 'file_size',
      header: () => t('admin.versions.columns.fileSize'),
      cell: ({ row }) => {
        return formatFileSize(row.original.file_size)
      },
    },
    {
      accessorKey: 'update_strategy',
      header: () => t('admin.versions.columns.strategy'),
      cell: ({ row }) => {
        const strategyClasses: Record<string, string> = {
          optional: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
          forced: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
        }
        const strategyLabels: Record<string, string> = {
          optional: t('admin.versions.strategies.optional'),
          forced: t('admin.versions.strategies.forced'),
        }
        return h(Badge, { class: strategyClasses[row.original.update_strategy] }, () => strategyLabels[row.original.update_strategy])
      },
    },
    {
      accessorKey: 'update_type',
      header: () => t('admin.versions.columns.type'),
      cell: ({ row }) => {
        const typeClasses: Record<string, string> = {
          full: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
          patch: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400',
        }
        const typeLabels: Record<string, string> = {
          full: t('admin.versions.types.full'),
          patch: t('admin.versions.types.patch'),
        }
        return h(Badge, { class: typeClasses[row.original.update_type] || typeClasses.full }, () => typeLabels[row.original.update_type] || row.original.update_type)
      },
    },
    {
      accessorKey: 'publish_status',
      header: () => t('admin.versions.columns.status'),
      cell: ({ row }) => {
        const status = row.original.publish_status || row.original.status || 'draft'
        const statusClasses: Record<string, string> = {
          draft: 'bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-400',
          published: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
          deprecated: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400',
          superseded: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400',
        }
        const statusLabels: Record<string, string> = {
          draft: t('admin.versions.status.draft'),
          published: t('admin.versions.status.published'),
          deprecated: t('admin.versions.status.deprecated'),
          superseded: t('admin.versions.status.superseded'),
          active: t('admin.versions.status.published'),
        }
        return h(Badge, { class: statusClasses[status] || statusClasses.draft }, () => statusLabels[status] || status)
      },
    },
    {
      accessorKey: 'delta_package',
      header: () => t('admin.versions.columns.deltaPackage'),
      cell: ({ row }) => {
        if (row.original.delta_package_path && row.original.delta_package_size) {
          return h('div', { class: 'flex items-center gap-1 text-xs text-muted-foreground' }, [
            h(Archive, { class: 'h-3 w-3' }),
            h('span', {}, formatFileSize(row.original.delta_package_size)),
          ])
        }
        return h('span', { class: 'text-muted-foreground' }, '-')
      },
    },
    {
      accessorKey: 'created_at',
      header: () => t('admin.versions.columns.createdAt'),
      cell: ({ row }) => {
        return h('span', { class: 'text-sm text-muted-foreground' }, new Date(row.original.created_at).toLocaleString('zh-CN'))
      },
    },
    {
      id: 'actions',
      header: () => t('admin.versions.columns.actions'),
      cell: ({ row }) => {
        const buttons = []

        // 下载按钮逻辑
        if (row.original.update_type === 'patch') {
          // 补丁版本：显示下载补丁包和下载完整包两个按钮
          if (row.original.file_path) {
            buttons.push(
              h(Button, {
                variant: 'ghost',
                size: 'sm',
                title: t('admin.versions.actions.downloadPatch'),
                onClick: () => options.onDownload(row.original),
              }, () => [
                h(Download, { class: 'h-4 w-4 text-orange-500' }),
              ]),
            )
          }
          // 补丁版本总是显示下载完整包按钮
          if (options.onDownloadFullPackage) {
            buttons.push(
              h(Button, {
                variant: 'ghost',
                size: 'sm',
                title: t('admin.versions.actions.downloadFullPackage'),
                onClick: () => options.onDownloadFullPackage?.(row.original),
              }, () => [
                h(Package, { class: 'h-4 w-4 text-green-500' }),
              ]),
            )
          }
        } else if (row.original.file_path) {
          // 全量版本：只显示一个下载按钮
          buttons.push(
            h(Button, {
              variant: 'ghost',
              size: 'sm',
              title: t('admin.versions.actions.download'),
              onClick: () => options.onDownload(row.original),
            }, () => [
              h(Download, { class: 'h-4 w-4' }),
            ]),
          )
        }

        // 增量包下载
        if (row.original.delta_package_path && options.onDownloadDelta) {
          buttons.push(
            h(Button, {
              variant: 'ghost',
              size: 'sm',
              title: t('admin.versions.actions.downloadDelta'),
              onClick: () => options.onDownloadDelta?.(row.original),
            }, () => [
              h(ArrowDownToLine, { class: 'h-4 w-4 text-blue-500' }),
            ]),
          )
        }

        // 编辑按钮
        buttons.push(
          h(Button, {
            variant: 'ghost',
            size: 'sm',
            title: t('admin.versions.actions.edit'),
            onClick: () => options.onEdit(row.original),
          }, () => [
            h(Edit, { class: 'h-4 w-4' }),
          ]),
        )

        // 发布状态操作按钮
        const publishStatus = row.original.publish_status || row.original.status || 'draft'

        if (publishStatus === 'draft' && options.onPublish) {
          buttons.push(
            h(Button, {
              variant: 'ghost',
              size: 'sm',
              title: t('admin.versions.actions.publish'),
              class: 'text-green-600 hover:text-green-700',
              onClick: () => options.onPublish?.(row.original),
            }, () => [
              h(Upload, { class: 'h-4 w-4' }),
            ]),
          )
        }

        if (publishStatus === 'published' && options.onDeprecate) {
          buttons.push(
            h(Button, {
              variant: 'ghost',
              size: 'sm',
              title: t('admin.versions.actions.deprecate'),
              class: 'text-orange-600 hover:text-orange-700',
              onClick: () => options.onDeprecate?.(row.original),
            }, () => [
              h(Archive, { class: 'h-4 w-4' }),
            ]),
          )
        }

        if (publishStatus === 'superseded' && options.onRollback) {
          buttons.push(
            h(Button, {
              variant: 'ghost',
              size: 'sm',
              title: t('admin.versions.actions.rollback'),
              class: 'text-blue-600 hover:text-blue-700',
              onClick: () => options.onRollback?.(row.original),
            }, () => [
              h(ArrowDownToLine, { class: 'h-4 w-4' }),
            ]),
          )
        }

        // 删除按钮
        buttons.push(
          h(Button, {
            variant: 'ghost',
            size: 'sm',
            title: t('admin.versions.actions.delete'),
            onClick: () => options.onDelete(row.original),
          }, () => [
            h(Trash2, { class: 'h-4 w-4 text-destructive' }),
          ]),
        )

        return h('div', { class: 'flex items-center justify-end gap-1' }, buttons)
      },
    },
  ]
}
