'use client'

import { useMemo } from 'react'
import Link from 'next/link'
import { useSession } from 'next-auth/react'
import {
  Check,
  ChevronDown,
  Eye,
  Handshake,
  LayoutDashboard,
  Scale,
  type LucideIcon,
} from 'lucide-react'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Button } from '@/components/ui/button'
import type { Route } from 'next'
import type { UserRole } from '@prisma/client'

export type RoleSwitchOption = { label: string; path: string; icon: LucideIcon }

export const ROLE_SWITCH_OPTIONS: Record<string, RoleSwitchOption> = {
  SUPER_ADMIN: { label: 'Admin View', path: '/admin', icon: LayoutDashboard },
  PROGRAM_ADMIN: { label: 'Admin View', path: '/admin', icon: LayoutDashboard },
  JURY_MEMBER: { label: 'Jury View', path: '/jury', icon: Scale },
  MENTOR: { label: 'Mentor View', path: '/mentor', icon: Handshake },
  OBSERVER: { label: 'Observer View', path: '/observer', icon: Eye },
}

export function useRoleSwitcher(currentBasePath: string): {
  currentOption: RoleSwitchOption | null
  switchableRoles: Array<[string, RoleSwitchOption]>
  isImpersonating: boolean
} {
  const { data: session } = useSession()
  const userRoles = (session?.user?.roles as UserRole[] | undefined) ?? []
  const isImpersonating = !!session?.user?.impersonating

  const { currentOption, switchableRoles } = useMemo(() => {
    const accessible = Object.entries(ROLE_SWITCH_OPTIONS)
      .filter(([role]) => userRoles.includes(role as UserRole))
      .filter((entry, i, arr) => arr.findIndex(([, o]) => o.path === entry[1].path) === i)
    const current = accessible.find(([, opt]) => opt.path === currentBasePath)?.[1] ?? null
    const others = accessible.filter(([, opt]) => opt.path !== currentBasePath)
    return { currentOption: current, switchableRoles: others }
  }, [userRoles, currentBasePath])

  return { currentOption, switchableRoles, isImpersonating }
}

/**
 * Top-right view-switcher pill. Trigger names the current view; the dropdown
 * lists alternative views. Hidden for single-view users and during impersonation.
 */
export function RoleSwitcherPill({ currentBasePath }: { currentBasePath: string }) {
  const { currentOption, switchableRoles, isImpersonating } = useRoleSwitcher(currentBasePath)
  if (switchableRoles.length === 0 || isImpersonating || !currentOption) return null

  const CurrentIcon = currentOption.icon

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="outline" size="sm" className="gap-1.5" aria-label="Switch view">
          <CurrentIcon className="h-3.5 w-3.5" />
          <span className="hidden sm:inline">{currentOption.label}</span>
          <ChevronDown className="h-3.5 w-3.5 opacity-60" />
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="min-w-52">
        <DropdownMenuLabel className="text-muted-foreground text-xs font-normal">
          Switch to another view
        </DropdownMenuLabel>
        <DropdownMenuItem disabled className="opacity-100">
          <CurrentIcon className="mr-2 h-4 w-4" />
          <span className="flex-1">{currentOption.label}</span>
          <Check className="text-muted-foreground h-3.5 w-3.5" />
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        {switchableRoles.map(([role, opt]) => (
          <DropdownMenuItem key={role} asChild>
            <Link href={opt.path as Route} className="flex cursor-pointer items-center">
              <opt.icon className="mr-2 h-4 w-4" />
              {opt.label}
            </Link>
          </DropdownMenuItem>
        ))}
      </DropdownMenuContent>
    </DropdownMenu>
  )
}
