'use client'

import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import { useTransition } from 'react'
import { ChevronDown } from 'lucide-react'
import { toast } from 'sonner'
import { Badge } from '@/components/ui/badge'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { AppIcon } from '@/components/shared/app-icon'
import { UserMenu } from '@/components/shared/user-menu'
import { NotificationsBell } from '@/components/shared/notifications-bell'
import { SoloNavStatusIndicators } from '@/components/solo/nav-status-indicators'
import { cn } from '@/lib/utils'
import { setActiveProductAction } from '@/actions/active-product'
import { resolveProductSwitchTarget } from '@/lib/product-switch-path'
import { debugProps } from '@/lib/debug'

interface NavBarProps {
  isDemo: boolean
  roles: string[]
  userId: string
  username: string
  email: string | null
  activeProduct: { id: string; name: string } | null
  products: { id: string; name: string }[]
  hasActiveSprint: boolean
  minQuotaPct: number
}

export function NavBar({
  isDemo,
  roles,
  userId,
  username,
  email,
  activeProduct,
  products,
  hasActiveSprint,
  minQuotaPct,
}: NavBarProps) {
  const pathname = usePathname()
  const router = useRouter()
  const [isPending, startTransition] = useTransition()

  const urlProductId = pathname.match(/^\/products\/([^/]+)/)?.[1] ?? null
  const displayActive =
    isDemo && urlProductId
      ? products.find(p => p.id === urlProductId) ?? activeProduct
      : activeProduct
  const activeId = displayActive?.id ?? null

  function handleSwitchProduct(productId: string) {
    if (productId === displayActive?.id) return
    if (isDemo) {
      router.push(`/products/${productId}`)
      return
    }
    startTransition(async () => {
      const result = await setActiveProductAction(productId)
      if (result?.error) {
        toast.error(typeof result.error === 'string' ? result.error : 'Wisselen mislukt')
        return
      }
      const next = products.find(p => p.id === productId)
      toast.success(`Actief product: ${next?.name ?? 'gewijzigd'}`)
      const target = resolveProductSwitchTarget(pathname, productId)
      if (target) router.push(target); else router.refresh()
    })
  }

  // Nav link helpers
  const disabledSpan = (label: string) => (
    <span
      key={label}
      className="px-3 py-1.5 rounded-md text-sm text-muted-foreground/40 cursor-not-allowed select-none"
    >
      {label}
    </span>
  )

  const navLink = (href: string, label: string, isActive: boolean) => (
    <Link
      key={label}
      href={href}
      className={cn(
        'px-3 py-1.5 rounded-md text-sm transition-colors',
        isActive
          ? 'bg-primary-container text-primary-container-foreground font-medium'
          : 'text-muted-foreground hover:text-foreground hover:bg-surface-container'
      )}
    >
      {label}
    </Link>
  )

  const sprintNode = () => {
    if (!activeId) return disabledSpan('Sprint')
    const isActive = pathname.includes('/sprint')
    if (!hasActiveSprint) {
      return (
        <TooltipProvider key="sprint">
          <Tooltip>
            <TooltipTrigger
              className="px-3 py-1.5 rounded-md text-sm text-muted-foreground/40 cursor-not-allowed select-none"
              aria-disabled="true"
            >
              Sprint
            </TooltipTrigger>
            <TooltipContent>Geen actieve sprint</TooltipContent>
          </Tooltip>
        </TooltipProvider>
      )
    }
    const href = `/products/${activeId}/sprint`
    return navLink(href, 'Sprint', isActive)
  }

  return (
    <header
      {...debugProps('nav-bar')}
      className="bg-surface-container-low border-b border-border h-14 flex items-center px-4 shrink-0"
    >
      {/* Links: logo + nav */}
      <div className="flex items-center gap-4 flex-1">
        <Link href="/" data-debug-id="nav-bar__app-icon" className="flex items-center gap-2 font-medium text-foreground">
          <AppIcon size={24} />
          <span className="text-primary font-semibold">Scrum4Me</span>
          {isDemo && (
            <Badge className="bg-warning text-warning-foreground text-xs px-2 py-0">
              Demo
            </Badge>
          )}
        </Link>

        <nav className="flex items-center gap-1 ml-2">
          {navLink('/dashboard', 'Producten', pathname.startsWith('/dashboard'))}
          {activeId
            ? navLink(
                `/products/${activeId}`,
                'Product Backlog',
                pathname.startsWith(`/products/${activeId}`) && !pathname.includes('/sprint') && !pathname.includes('/solo')
              )
            : disabledSpan('Product Backlog')}
          {sprintNode()}
          {activeId
            ? navLink(
                `/products/${activeId}/solo`,
                'Solo',
                pathname.includes('/solo')
              )
            : disabledSpan('Solo')}
          {navLink('/insights', 'Insights', pathname.startsWith('/insights'))}
          {navLink('/ideas', 'Ideas', pathname.startsWith('/ideas'))}
          {navLink('/jobs', 'Jobs', pathname.startsWith('/jobs'))}
        </nav>
      </div>

      {/* Midden: actief product */}
      <div className="flex items-center justify-center">
        {displayActive ? (
          <DropdownMenu>
            <DropdownMenuTrigger
              disabled={isPending}
              data-debug-id="nav-bar__product-switcher"
              className="flex items-center gap-1 text-sm font-medium text-foreground hover:text-primary transition-colors px-2 rounded-md hover:bg-surface-container focus:outline-none"
            >
              <span className="truncate max-w-[180px]">
                {displayActive.name.length > 22
                  ? displayActive.name.slice(0, 22) + '…'
                  : displayActive.name}
              </span>
              <ChevronDown className="w-3.5 h-3.5 shrink-0 text-muted-foreground" />
            </DropdownMenuTrigger>
            <DropdownMenuContent align="center" className="w-56">
              {products.map(p => (
                <DropdownMenuItem
                  key={p.id}
                  onClick={() => p.id !== displayActive.id && handleSwitchProduct(p.id)}
                  className={cn(
                    p.id === displayActive.id && 'bg-primary-container text-primary-container-foreground font-medium'
                  )}
                >
                  <span className="truncate">{p.name}</span>
                </DropdownMenuItem>
              ))}
              <DropdownMenuSeparator />
              <DropdownMenuItem>
                <Link href="/dashboard" className="w-full">
                  Producten beheren →
                </Link>
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        ) : (
          <span className="text-sm text-muted-foreground/50 select-none">Geen actief product</span>
        )}
      </div>

      {/* Rechts: solo-status + notifications + account-menu */}
      <div className="flex items-center gap-2 flex-1 justify-end">
        <SoloNavStatusIndicators hasActiveProduct={!!activeProduct} minQuotaPct={minQuotaPct} />
        <NotificationsBell currentUserId={userId} isDemo={isDemo} />
        <span data-debug-id="nav-bar__user-menu">
          <UserMenu userId={userId} username={username} email={email} roles={roles} />
        </span>
      </div>
    </header>
  )
}
