'use client'

import { useState } from 'react'
import Link from 'next/link'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { toast } from 'sonner'
import {
  MoreHorizontal,
  Mail,
  UserCog,
  Trash2,
  Loader2,
  Shield,
  Check,
} from 'lucide-react'

type Role = 'SUPER_ADMIN' | 'PROGRAM_ADMIN' | 'JURY_MEMBER' | 'MENTOR' | 'OBSERVER'

const ROLE_LABELS: Record<Role, string> = {
  SUPER_ADMIN: 'Super Admin',
  PROGRAM_ADMIN: 'Program Admin',
  JURY_MEMBER: 'Jury Member',
  MENTOR: 'Mentor',
  OBSERVER: 'Observer',
}

interface UserActionsProps {
  userId: string
  userEmail: string
  userStatus: string
  userRole: Role
  currentUserRole?: Role
}

export function UserActions({ userId, userEmail, userStatus, userRole, currentUserRole }: UserActionsProps) {
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)
  const [isSending, setIsSending] = useState(false)

  const utils = trpc.useUtils()
  const sendInvitation = trpc.user.sendInvitation.useMutation()
  const deleteUser = trpc.user.delete.useMutation({
    onSuccess: () => {
      utils.user.list.invalidate()
    },
  })
  const updateUser = trpc.user.update.useMutation({
    onSuccess: () => {
      utils.user.list.invalidate()
      toast.success('Role updated successfully')
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to update role')
    },
  })

  const isSuperAdmin = currentUserRole === 'SUPER_ADMIN'

  // Determine which roles can be assigned
  const getAvailableRoles = (): Role[] => {
    if (isSuperAdmin) {
      return ['SUPER_ADMIN', 'PROGRAM_ADMIN', 'JURY_MEMBER', 'MENTOR', 'OBSERVER']
    }
    // Program admins can only assign lower roles
    return ['JURY_MEMBER', 'MENTOR', 'OBSERVER']
  }

  // Can this user's role be changed by the current user?
  const canChangeRole = isSuperAdmin || (!['SUPER_ADMIN', 'PROGRAM_ADMIN'].includes(userRole))

  const handleRoleChange = (newRole: Role) => {
    if (newRole === userRole) return
    updateUser.mutate({ id: userId, role: newRole })
  }

  const handleSendInvitation = async () => {
    if (userStatus !== 'NONE' && userStatus !== 'INVITED') {
      toast.error('User has already accepted their invitation')
      return
    }

    setIsSending(true)
    try {
      await sendInvitation.mutateAsync({ userId })
      toast.success(`Invitation sent to ${userEmail}`)
      // Invalidate in case status changed
      utils.user.list.invalidate()
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Failed to send invitation')
    } finally {
      setIsSending(false)
    }
  }

  const handleDelete = async () => {
    try {
      await deleteUser.mutateAsync({ id: userId })
      toast.success('User deleted successfully')
      setShowDeleteDialog(false)
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Failed to delete user')
    }
  }

  return (
    <>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="ghost" size="icon">
            {isSending ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <MoreHorizontal className="h-4 w-4" />
            )}
            <span className="sr-only">Actions</span>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DropdownMenuItem asChild>
            <Link href={`/admin/members/${userId}`}>
              <UserCog className="mr-2 h-4 w-4" />
              Edit
            </Link>
          </DropdownMenuItem>
          {canChangeRole && (
            <DropdownMenuSub>
              <DropdownMenuSubTrigger disabled={updateUser.isPending}>
                <Shield className="mr-2 h-4 w-4" />
                {updateUser.isPending ? 'Updating...' : 'Change Role'}
              </DropdownMenuSubTrigger>
              <DropdownMenuSubContent>
                {getAvailableRoles().map((role) => (
                  <DropdownMenuItem
                    key={role}
                    onClick={() => handleRoleChange(role)}
                    disabled={role === userRole}
                  >
                    {role === userRole && <Check className="mr-2 h-4 w-4" />}
                    <span className={role === userRole ? 'font-medium' : role !== userRole ? 'ml-6' : ''}>
                      {ROLE_LABELS[role]}
                    </span>
                  </DropdownMenuItem>
                ))}
              </DropdownMenuSubContent>
            </DropdownMenuSub>
          )}
          <DropdownMenuItem
            onClick={handleSendInvitation}
            disabled={(userStatus !== 'NONE' && userStatus !== 'INVITED') || isSending}
          >
            <Mail className="mr-2 h-4 w-4" />
            {isSending ? 'Sending...' : 'Send Invite'}
          </DropdownMenuItem>
          <DropdownMenuSeparator />
          <DropdownMenuItem
            className="text-destructive focus:text-destructive"
            onClick={() => setShowDeleteDialog(true)}
          >
            <Trash2 className="mr-2 h-4 w-4" />
            Remove
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>

      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete User</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to delete {userEmail}? This action cannot be
              undone and will remove all their assignments and evaluations.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDelete}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              {deleteUser.isPending ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : null}
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}

interface UserMobileActionsProps {
  userId: string
  userEmail: string
  userStatus: string
  userRole: Role
  currentUserRole?: Role
}

export function UserMobileActions({
  userId,
  userEmail,
  userStatus,
  userRole,
  currentUserRole,
}: UserMobileActionsProps) {
  const [isSending, setIsSending] = useState(false)
  const utils = trpc.useUtils()
  const sendInvitation = trpc.user.sendInvitation.useMutation()
  const updateUser = trpc.user.update.useMutation({
    onSuccess: () => {
      utils.user.list.invalidate()
      toast.success('Role updated successfully')
    },
    onError: (error) => {
      toast.error(error.message || 'Failed to update role')
    },
  })

  const isSuperAdmin = currentUserRole === 'SUPER_ADMIN'
  const canChangeRole = isSuperAdmin || (!['SUPER_ADMIN', 'PROGRAM_ADMIN'].includes(userRole))

  const handleSendInvitation = async () => {
    if (userStatus !== 'NONE' && userStatus !== 'INVITED') {
      toast.error('User has already accepted their invitation')
      return
    }

    setIsSending(true)
    try {
      await sendInvitation.mutateAsync({ userId })
      toast.success(`Invitation sent to ${userEmail}`)
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Failed to send invitation')
    } finally {
      setIsSending(false)
    }
  }

  return (
    <div className="space-y-2 pt-2">
      <div className="flex gap-2">
        <Button variant="outline" size="sm" className="flex-1" asChild>
          <Link href={`/admin/members/${userId}`}>
            <UserCog className="mr-2 h-4 w-4" />
            Edit
          </Link>
        </Button>
        <Button
          variant="outline"
          size="sm"
          className="flex-1"
          onClick={handleSendInvitation}
          disabled={(userStatus !== 'NONE' && userStatus !== 'INVITED') || isSending}
        >
          {isSending ? (
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          ) : (
            <Mail className="mr-2 h-4 w-4" />
          )}
          Invite
        </Button>
      </div>
      {canChangeRole && (
        <select
          value={userRole}
          onChange={(e) => updateUser.mutate({ id: userId, role: e.target.value as Role })}
          disabled={updateUser.isPending}
          className="w-full rounded-md border border-input bg-background px-3 py-1.5 text-sm"
        >
          {(isSuperAdmin
            ? (['SUPER_ADMIN', 'PROGRAM_ADMIN', 'JURY_MEMBER', 'MENTOR', 'OBSERVER'] as Role[])
            : (['JURY_MEMBER', 'MENTOR', 'OBSERVER'] as Role[])
          ).map((role) => (
            <option key={role} value={role}>
              {ROLE_LABELS[role]}
            </option>
          ))}
        </select>
      )}
    </div>
  )
}
