"use client"

import { ColumnDef } from "@tanstack/react-table"
import { Role } from "@/lib/schemas/user"
import { UserActions } from "./user-actions"
import { Badge } from "@/components/ui/badge"

export type UserColumn = {
  id: string
  name: string | null
  email: string
  studentId: string | null
  role: Role
  createdAt: Date
  currentUserRole?: Role
}

export const columns: ColumnDef<UserColumn>[] = [
  {
    accessorKey: "name",
    header: "Name",
    cell: ({ row }) => {
      const user = row.original
      return (
        <div className="flex flex-col">
          <span className="font-medium">{user.name || "N/A"}</span>
          <span className="text-xs text-muted-foreground">{user.email}</span>
        </div>
      )
    }
  },
  {
    accessorKey: "studentId",
    header: "Student ID",
    cell: ({ row }) => row.getValue("studentId") || "—"
  },
  {
    accessorKey: "role",
    header: "Role",
    cell: ({ row }) => {
      const role = row.getValue("role") as Role
      return (
        <Badge variant={role === "ADMIN" ? "destructive" : role === "STAFF" ? "default" : "secondary"}>
          {role}
        </Badge>
      )
    }
  },
  {
    accessorKey: "createdAt",
    header: "Joined At",
    cell: ({ row }) => {
      return new Date(row.getValue("createdAt")).toLocaleDateString()
    }
  },
  {
    id: "actions",
    header: "Change Role",
    cell: ({ row }) => {
      const user = row.original
      const canEdit = user.currentUserRole === "ADMIN"
      return <UserActions userId={user.id} initialRole={user.role} disabled={!canEdit} />
    }
  }
]
