import type { User } from '@admin/types/auth'
import type { ColumnDef } from '@tanstack/react-table'
import { SortIndicator } from '@admin/components/shared/sort-indicator'
import { Avatar, AvatarFallback } from '@admin/components/ui/avatar'
import { Badge } from '@admin/components/ui/badge'
import { Button } from '@admin/components/ui/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger
} from '@admin/components/ui/dropdown-menu'
import { UserRole } from '@admin/types/auth'
import { getUserInitials } from '@admin/utils/user/get-user-initials'
import { Edit, MoreHorizontal, ShieldCheck } from 'lucide-react'
import { ChangePasswordDialog } from './change-password-dialog'
import { DeleteUserDialog } from './delete-user-dialog'
import { EditRoleDialog } from './edit-role-dialog'

export const columns: ColumnDef<User>[] = [
  {
    accessorKey: 'email',
    header: ({ column }) => {
      const sortDirection = column.getIsSorted()

      return (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
          className="group w-full min-w-0 scale-100! justify-start overflow-hidden rounded-none border-none bg-transparent! px-0!"
        >
          <span className="truncate">User</span>
          <SortIndicator direction={sortDirection} />
        </Button>
      )
    },
    cell: ({ row }) => {
      const email = row.getValue('email') as string
      const name = row.original.name
      return (
        <div className="flex items-center gap-3">
          <Avatar className="size-8">
            <AvatarFallback>{getUserInitials(name || email)}</AvatarFallback>
          </Avatar>
          <div className="flex flex-col">
            <div className="font-medium">{name || 'N/A'}</div>
            <div className="text-sm text-muted-foreground">{email}</div>
          </div>
        </div>
      )
    }
  },
  {
    accessorKey: 'emailVerified',
    header: 'Status',
    cell: ({ row }) => {
      const verified = row.getValue('emailVerified') as boolean
      return (
        <Badge variant="outline">
          {verified ? (
            <span className="flex items-center gap-1">
              <ShieldCheck className="size-3.5" />
              Verified
            </span>
          ) : (
            <span className="flex items-center gap-1">
              <ShieldCheck className="size-3.5" />
              Unverified
            </span>
          )}
        </Badge>
      )
    }
  },
  {
    accessorKey: 'role',
    header: 'Role',
    cell: ({ row, table }) => {
      const role = row.getValue('role') as string
      const currentUser = table.options.meta?.currentUser
      const isCurrentUser = currentUser?.email === row.original.email

      if (isCurrentUser) {
        return (
          <Badge variant="outline" className="capitalize">
            {role} (you)
          </Badge>
        )
      }

      return (
        <EditRoleDialog
          userId={row.original.id}
          currentRole={row.original.role}
          userName={row.original.name}
        >
          <Badge variant="outline" className="cursor-pointer capitalize">
            <span className="flex items-center gap-1">
              {role}
              <Edit className="size-3" />
            </span>
          </Badge>
        </EditRoleDialog>
      )
    }
  },
  {
    accessorKey: 'createdAt',
    header: ({ column }) => {
      const sortDirection = column.getIsSorted()

      return (
        <Button
          variant="ghost"
          onClick={() => column.toggleSorting(column.getIsSorted() === 'asc')}
          className="group w-full min-w-0 scale-100! justify-start overflow-hidden rounded-none border-none bg-transparent! px-0!"
        >
          <span className="truncate">Joined</span>
          <SortIndicator direction={sortDirection} />
        </Button>
      )
    },
    cell: ({ row }) => {
      const date = new Date(row.getValue('createdAt'))
      return (
        <div className="text-sm">
          {date.toLocaleDateString('en-US', {
            month: 'short',
            day: 'numeric',
            year: 'numeric'
          })}
        </div>
      )
    }
  },
  {
    id: 'actions',
    size: 80,
    enableResizing: false,
    meta: { width: '80px' },
    cell: ({ row, table }) => {
      const currentUser = table.options.meta?.currentUser
      const isCurrentUser =
        currentUser?.id === row.original.id || currentUser?.email === row.original.email
      const canChangePassword = isCurrentUser || currentUser?.role === UserRole.ADMIN

      if (!isCurrentUser && !currentUser) return null

      return (
        <div className="flex justify-end">
          <DropdownMenu>
            <DropdownMenuTrigger render={<Button variant="ghost" className="size-8 p-0" />}>
              <span className="sr-only">Open menu</span>
              <MoreHorizontal className="size-4" />
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              {!isCurrentUser ? (
                <DeleteUserDialog
                  userId={row.original.id}
                  userName={row.original.name}
                  isCurrentUser={isCurrentUser}
                />
              ) : null}
              {canChangePassword ? (
                <ChangePasswordDialog
                  userId={row.original.id}
                  userName={row.original.name}
                  userEmail={row.original.email}
                  isCurrentUser={isCurrentUser}
                />
              ) : null}
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      )
    }
  }
]
