'use client'

import { useTransition } from 'react'
import Link from 'next/link'
import { Settings, Sun, Globe, LogOut, BookOpen, Shield } from 'lucide-react'
import { logoutAction } from '@/actions/auth'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { Badge } from '@/components/ui/badge'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { debugProps } from '@/lib/debug'

const ROLE_LABELS: Record<string, string> = {
  PRODUCT_OWNER: 'Product Owner',
  SCRUM_MASTER: 'Scrum Master',
  DEVELOPER: 'Developer',
  ADMIN: 'Admin',
}

interface UserMenuProps {
  userId: string
  username: string
  email: string | null
  roles: string[]
}

export function UserMenu({ userId, username, email, roles }: UserMenuProps) {
  const initials = username.slice(0, 2).toUpperCase()
  const roleLabels = roles.map((r) => ROLE_LABELS[r]).filter(Boolean)
  const subtitle = email?.trim() ? email.trim() : 'Lokaal account'
  const [pendingLogout, startLogout] = useTransition()

  // Server Action direct aanroepen — geen form/ref-dance. Eerdere implementatie
  // gebruikte een hidden form binnen DropdownMenuContent; die unmount op
  // onSelect en in deze base-ui-versie kwam de submit niet door.
  function handleLogout() {
    startLogout(async () => {
      await logoutAction()
    })
  }

  return (
    <span {...debugProps('user-menu')}>
    <DropdownMenu>
        <DropdownMenuTrigger
        className="rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-2 focus-visible:ring-offset-background"
        aria-label="Accountmenu openen"
      >
        <Avatar size="default">
          <AvatarImage src={`/api/users/${userId}/avatar`} alt={username} />
          <AvatarFallback className="bg-primary-container text-primary-container-foreground">
            {initials}
          </AvatarFallback>
        </Avatar>
      </DropdownMenuTrigger>

      <DropdownMenuContent align="end" sideOffset={8} className="w-72">
        <div className="flex items-center gap-3 px-2 py-2">
          <Avatar size="lg">
            <AvatarImage src={`/api/users/${userId}/avatar`} alt={username} />
            <AvatarFallback className="bg-primary-container text-primary-container-foreground">
              {initials}
            </AvatarFallback>
          </Avatar>
          <div className="min-w-0 flex-1">
            <div className="text-sm font-medium text-foreground truncate">{username}</div>
            <div className="text-xs text-muted-foreground truncate">{subtitle}</div>
          </div>
        </div>

        {roleLabels.length > 0 && (
          <>
            <DropdownMenuSeparator />
            <DropdownMenuGroup>
              <DropdownMenuLabel className="text-xs uppercase tracking-wide text-muted-foreground">
                Rollen
              </DropdownMenuLabel>
              <div className="px-2 pb-2 text-sm text-foreground">
                {roleLabels.join(', ')}
              </div>
            </DropdownMenuGroup>
          </>
        )}

        <DropdownMenuSeparator />

        <DropdownMenuItem render={<Link href="/settings" />}>
          <Settings className="mr-2 h-4 w-4" />
          <span>Instellingen</span>
        </DropdownMenuItem>

        <DropdownMenuItem disabled className="opacity-60">
          <Sun className="mr-2 h-4 w-4" />
          <span>Thema: licht</span>
          <Badge className="ml-auto bg-muted text-muted-foreground text-[10px] px-1.5 py-0">
            Binnenkort
          </Badge>
        </DropdownMenuItem>

        <DropdownMenuItem disabled className="opacity-60">
          <Globe className="mr-2 h-4 w-4" />
          <span>Taal: Nederlands</span>
          <Badge className="ml-auto bg-muted text-muted-foreground text-[10px] px-1.5 py-0">
            Binnenkort
          </Badge>
        </DropdownMenuItem>

        <DropdownMenuSeparator />

        <DropdownMenuItem render={<Link href="/manual" />}>
          <BookOpen className="mr-2 h-4 w-4" />
          <span>Manual</span>
        </DropdownMenuItem>

        {roles.includes('ADMIN') && (
          <DropdownMenuItem render={<Link href="/admin" />}>
            <Shield className="mr-2 h-4 w-4" />
            <span>Admin</span>
          </DropdownMenuItem>
        )}

        <DropdownMenuSeparator />

        <DropdownMenuItem
          onClick={handleLogout}
          onSelect={handleLogout}
          disabled={pendingLogout}
          className="cursor-pointer"
        >
          <LogOut className="mr-2 h-4 w-4" />
          <span>{pendingLogout ? 'Uitloggen…' : 'Uitloggen'}</span>
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
    </span>
  )
}
