'use client'

import { ColumnDef } from '@tanstack/react-table'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Edit, Trash2, MoreHorizontal } from 'lucide-react'
import { formatDate } from '@/lib/format'
import { userStatusOptions } from '@/lib/schema/user'
import { Checkbox } from '@/components/ui/checkbox'
import { DataTableColumnHeader } from '@/components/data-table/column-header'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import type { User } from '@/server/routers/users'

// 操作回调类型
export type UserActions = {
  onEdit: (userId: string) => void
  onDelete: (userId: string) => void
}

// 列定义选项类型
export type UserColumnsOptions = {
  roles?: Array<{ id: number; name: string }>
  permissions?: Array<{ id: number; name: string }>
  depts?: Array<{ code: string; name: string; fullName: string }>
}

// 创建用户表格列定义
export const createUserColumns = (
  actions: UserActions,
  options: UserColumnsOptions = {}
): ColumnDef<User>[] => [
  {
    id: "select",
    header: ({ table }) => (
      <Checkbox
        checked={
          table.getIsAllPageRowsSelected() ||
          (table.getIsSomePageRowsSelected() && "indeterminate")
        }
        onCheckedChange={(value) =>
          table.toggleAllPageRowsSelected(!!value)
        }
        aria-label="Select all"
      />
    ),
    cell: ({ row }) => (
      <Checkbox
        checked={row.getIsSelected()}
        onCheckedChange={(value) => row.toggleSelected(!!value)}
        aria-label="Select row"
      />
    ),
    size: 32,
    enableSorting: false,
    enableHiding: false,
  },
  {
    id: 'id',
    accessorKey: 'id',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title="用户ID" />
    ),
    cell: ({ row }) => <div className="font-medium">{row.original.id}</div>,
    enableColumnFilter: true,
    meta: {
      label: '用户ID',
      filter: {
        placeholder: '请输入用户ID',
        variant: 'text',
      }
    },
  },
  {
    id: 'name',
    accessorKey: 'name',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title="姓名" />
    ),
    cell: ({ row }) => <div>{row.original.name || '-'}</div>,
    enableColumnFilter: true,
    meta: {
      label: '姓名',
      filter: {
        placeholder: '请输入姓名',
        variant: 'text',
      }
    },
  },
  {
    id: 'status',
    accessorKey: 'status',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title="状态" />
    ),
    cell: ({ row }) => {
      const status = row.original.status
      return (
        <Badge variant={status === '在校' ? 'default' : 'secondary'}>
          {status || '未知'}
        </Badge>
      )
    },
    enableColumnFilter: true,
    meta: {
      label: '状态',
      filter: {
        variant: 'select',
        options: userStatusOptions,
      }
    },
  },
  {
    id: 'dept',
    accessorKey: 'dept',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title="所属院系" />
    ),
    cell: ({ row }) => <div>{row.original.dept?.name || '-'}</div>,
    enableColumnFilter: true,
    meta: {
      label: '所属院系',
      filter: {
        variant: 'multiSelect',
        options: options.depts?.map(dept => ({
          id: dept.code,
          name: dept.fullName,
        })) || [],
      }
    },
  },
  {
    id: 'roles',
    accessorKey: 'roles',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title="角色" />
    ),
    cell: ({ row }) => {
      const roles = row.original.roles
      return (
        <div className="flex flex-wrap gap-1">
          {roles.map((role) => (
            <Badge key={role.id} variant="secondary">
              {role.name}
            </Badge>
          ))}
        </div>
      )
    },
    enableColumnFilter: true,
    enableSorting: false,
    meta: {
      label: '角色',
      filter: {
        variant: 'select',
        options: options.roles?.map(role => ({
          id: role.id.toString(),
          name: role.name,
        })) || [],
      }
    },
  },
  {
    id: 'permissions',
    accessorFn: row => Array.from(
      new Set(
        row.roles.flatMap((role) => role.permissions.map((p) => p.name))
      )
    ),
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title="权限" />
    ),
    cell: ({ getValue }) => {
      return (
        <div className="flex flex-wrap gap-1">
          {getValue<string[]>().map((permName) => (
            <Badge key={permName} variant="outline" className="text-xs">
              {permName}
            </Badge>
          ))}
        </div>
      )
    },
    enableColumnFilter: true,
    enableSorting: false,
    meta: {
      label: '权限',
      filter: {
        variant: 'select',
        options: options.permissions?.map(permission => ({
          id: permission.id.toString(),
          name: permission.name,
        })) || [],
      }
    },
  },
  {
    id: 'lastLoginAt',
    accessorKey: 'lastLoginAt',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title="最后登录" />
    ),
    cell: ({ row }) => {
      const lastLoginAt = row.original.lastLoginAt as Date | null
      return <div>{lastLoginAt ? formatDate(lastLoginAt) : '从未登录'}</div>
    },
    meta: {
      label: '最后登录',
    },
  },
  {
    id: 'createdAt',
    accessorKey: 'createdAt',
    header: ({ column }) => (
      <DataTableColumnHeader column={column} title="创建时间" />
    ),
    cell: ({ row }) => {
      return <div>{formatDate(row.original.createdAt) || '-'}</div>
    },
    meta: {
      label: '创建时间',
    }
  },
  {
    id: 'actions',
    cell: ({ row }) => {
      const user = row.original
      return (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="icon" className="h-6 w-6 md:w-9">
              <MoreHorizontal className="h-4 w-4" />
              <span className="sr-only">打开菜单</span>
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => actions.onEdit(user.id)}>
              <Edit className="h-4 w-4" />
              编辑
            </DropdownMenuItem>
            <DropdownMenuItem
              variant="destructive"
              onClick={() => actions.onDelete(user.id)}
            >
              <Trash2 className="h-4 w-4" />
              删除
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      )
    },
    size: 32,
    enableSorting: false,
    enableHiding: false,
  },
]