'use client'

import { useSession } from 'next-auth/react'
import { trpc } from '@/lib/trpc/client'
import { Button } from '@/components/ui/button'
import { ArrowLeft, Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import type { UserRole } from '@prisma/client'

export function ImpersonationBanner() {
  const { data: session, update } = useSession()
  const endImpersonation = trpc.user.endImpersonation.useMutation()

  if (!session?.user?.impersonating) return null

  const handleReturn = async () => {
    try {
      await endImpersonation.mutateAsync()
      await update({ endImpersonation: true })
      window.location.href = '/admin/members'
    } catch (error) {
      toast.error(error instanceof Error ? error.message : 'Failed to end impersonation')
    }
  }

  // Show every role the impersonated user holds (multi-role support).
  const roles = (session.user.roles as UserRole[] | undefined) ?? [session.user.role as UserRole]
  const rolesLabel = roles.map((r) => r.replace(/_/g, ' ')).join(', ')

  return (
    // pointer-events-none on the wrapper so the banner doesn't intercept clicks
    // on anything underneath (e.g., the user-menu dropdown). The button inside
    // re-enables pointer-events on itself only.
    <div className="pointer-events-none fixed top-0 left-0 right-0 z-50 flex items-center justify-center gap-3 bg-red-600 px-4 py-1.5 text-sm text-white shadow-md">
      <span>
        Impersonating <strong>{session.user.name || session.user.email}</strong>{' '}
        ({rolesLabel})
      </span>
      <Button
        size="sm"
        variant="secondary"
        className="pointer-events-auto h-6 px-3 text-xs"
        onClick={handleReturn}
        disabled={endImpersonation.isPending}
      >
        {endImpersonation.isPending ? (
          <Loader2 className="mr-1 h-3 w-3 animate-spin" />
        ) : (
          <ArrowLeft className="mr-1 h-3 w-3" />
        )}
        Return to Admin
      </Button>
    </div>
  )
}
