'use client'

import {
  ChevronDown,
  CirclePlayIcon,
  ShoppingCartIcon,
  GraduationCapIcon,
  LayoutDashboardIcon,
  LightbulbIcon,
  LogOutIcon,
  UserIcon,
  type LucideIcon
} from 'lucide-react'
import { Link } from 'react-router'

import { initials } from '../lib/utils'
import { Avatar, AvatarFallback } from './ui/avatar'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger
} from './ui/dropdown-menu'

type NavItem = {
  appId: string
  title: string
  url: string
  icon: LucideIcon
  scope?: string[]
}

const apps: NavItem[] = [
  {
    appId: 'saladeaula',
    title: 'Sala de aula',
    url: '//scorm.eduseg.workers.dev',
    icon: GraduationCapIcon
  },
  {
    appId: 'admin',
    title: 'Administrador',
    url: '//admin.saladeaula.digital',
    icon: LayoutDashboardIcon,
    scope: ['apps:admin']
  },
  {
    appId: 'studio',
    title: 'EDUSEG® Estúdio',
    url: '//studio.saladeaula.digital',
    icon: CirclePlayIcon,
    scope: ['apps:studio']
  },
  {
    appId: 'insights',
    title: 'EDUSEG® Insights',
    url: '//insights.saladeaula.digital',
    icon: LightbulbIcon,
    scope: ['apps:insights']
  }
]

export function NavUser({
  user,
  excludeApps
}: {
  user: {
    name: string
    email: string
    scope: string
  }
  excludeApps: string[]
}) {
  const userScope = user.scope.split(' ')

  return (
    <DropdownMenu>
      <DropdownMenuTrigger className="cursor-pointer" asChild>
        <div className="relative">
          <Avatar className="size-10">
            <AvatarFallback>{initials(user.name)}</AvatarFallback>
          </Avatar>
          <ChevronDown className="size-3.5 absolute -bottom-px -right-px bg-gray-200 dark:bg-neutral-700 border border-background rounded-full px-px" />
        </div>
      </DropdownMenuTrigger>
      <DropdownMenuContent
        className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
        side="bottom"
        align="end"
        sideOffset={4}
      >
        <DropdownMenuLabel className="p-0 font-normal">
          <div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
            <Avatar className="size-10">
              <AvatarFallback>{initials(user.name)}</AvatarFallback>
            </Avatar>
            <div className="grid flex-1 text-left text-sm leading-tight">
              <span className="truncate font-medium">{user.name}</span>
              <span className="truncate text-xs text-muted-foreground">
                {user.email}
              </span>
            </div>
          </div>
        </DropdownMenuLabel>

        <DropdownMenuGroup>
          <DropdownMenuSeparator />
          <DropdownMenuItem asChild>
            <Link
              to="//scorm.eduseg.workers.dev/settings"
              className="cursor-pointer"
            >
              <UserIcon />
              Minha conta
            </Link>
          </DropdownMenuItem>
          <DropdownMenuItem asChild>
            <Link
              to="//scorm.eduseg.workers.dev/history"
              className="cursor-pointer"
            >
              <ShoppingCartIcon />
              Histórico de pagamentos
            </Link>
          </DropdownMenuItem>
        </DropdownMenuGroup>

        <DropdownMenuGroup>
          {grantIfHas(
            ['apps:admin', 'apps:studio', 'apps:insights'],
            userScope,
            'any'
          ) && (
            <>
              <DropdownMenuSeparator />
              <DropdownMenuLabel className="text-muted-foreground text-sm">
                Aplicações
              </DropdownMenuLabel>
            </>
          )}

          {apps
            .filter(({ appId }) => !excludeApps.includes(appId))
            .filter(({ scope = [] }) => grantIfHas(scope, userScope))
            .map(({ appId, title, url, icon: Icon }) => (
              <DropdownMenuItem key={appId} asChild>
                <Link to={url} className="cursor-pointer">
                  <Icon /> {title}
                </Link>
              </DropdownMenuItem>
            ))}
        </DropdownMenuGroup>

        <DropdownMenuSeparator />
        <DropdownMenuItem asChild>
          <Link to="/logout" className="cursor-pointer" reloadDocument>
            <LogOutIcon />
            Sair
          </Link>
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  )
}

function grantIfHas(
  required: string[],
  granted: string[],
  mode: 'all' | 'any' = 'all'
): boolean {
  const grantedSet: Set<string> = new Set(granted)

  if (mode === 'all') {
    return required.every((scope) => grantedSet.has(scope))
  }

  return required.some((scope) => grantedSet.has(scope))
}
