'use client';

import { usePathname } from 'next/navigation';
import Link from 'next/link';
import { cn } from '@/lib/utils';
import {
  LayoutDashboard,
  Server,
  Database,
  Activity,
  HardDrive,
  Sparkles,
  Users,
  TrendingUp,
  BarChart3,
  GitCompare,
  Brain,
  Search,
  AlertTriangle,
  ChevronDown,
  ShoppingCart,
  ShieldAlert,
} from 'lucide-react';
import {
  NavigationMenu,
  NavigationMenuItem,
  NavigationMenuLink,
  NavigationMenuList,
  navigationMenuTriggerStyle,
} from '@/components/ui/navigation-menu';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Button } from '@/components/ui/button';
import { ThemeToggle } from '@/components/theme-toggle';
import { StatusIndicator } from '@/components/navigation/status-indicator';
import { UserMenu } from '@/components/navigation/user-menu';
import { MobileNav } from '@/components/navigation/mobile-nav';
import { useSession } from '@/lib/auth-client';

interface NavItem {
  title: string;
  href?: string;
  icon?: React.ElementType;
  description?: string;
  children?: NavItem[];
}

const navigationItems: NavItem[] = [
  {
    title: 'Dashboard',
    href: '/',
    icon: LayoutDashboard,
    description: 'Overview and quick access'
  },
  {
    title: 'Configuration Items',
    href: '/configuration-items',
    icon: Server,
    description: 'Manage IT assets and devices'
  },
  {
    title: 'PAX8',
    href: '/pax8',
    icon: ShoppingCart,
    description: 'PAX8 companies, subscriptions, and cost breakdown'
  },
  {
    title: 'Phishing',
    href: '/phishing',
    icon: ShieldAlert,
    description: 'Phishing/spam campaign triage, evidence, and remediation approval'
  },
  {
    title: 'Backup Status',
    icon: HardDrive,
    children: [
      {
        title: 'Backup Status',
        href: '/backup-status',
        icon: HardDrive,
        description: 'Veeam backup health and compliance'
      },
      {
        title: 'RPO Comparison',
        href: '/veeam-comparison',
        icon: GitCompare,
        description: 'Pulse RPO shadow vs Datto RMM ticket comparison'
      },
      {
        title: 'Ticket Analysis',
        href: '/veeam-analysis',
        icon: Brain,
        description: 'AI classification of backup tickets — patterns, skills, SOP gaps'
      },
    ]
  },
  {
    title: 'Engagement',
    icon: Users,
    children: [
      {
        title: 'Overview',
        href: '/engagement',
        icon: Users,
        description: 'Staff activity and engagement metrics',
      },
      {
        title: 'Employee Profile',
        href: '/engagement/profile',
        icon: TrendingUp,
        description: '12-month activity calendar and performance profile',
      },
    ],
  },
  {
    title: 'Analyzer',
    icon: Sparkles,
    children: [
      {
        title: 'Browse Tickets',
        href: '/analyzer/tickets',
        icon: Search,
        description: 'Filter tickets by period, client, or issue type — pick one to analyze',
      },
      {
        title: 'Aggregate Reports',
        href: '/analyzer/reports',
        icon: BarChart3,
        description: 'Cross-ticket pattern analysis: documentation gaps, process gaps, recurrence clusters',
      },
      {
        title: 'Needs Review',
        href: '/analyzer/queue',
        icon: AlertTriangle,
        description: 'Analyses flagged for human review (low confidence or cost-ceiling skipped Opus)',
      },
      {
        title: 'IT Glue — Applications',
        href: '/analyzer/itglue/applications',
        icon: Database,
        description: 'Audit IT Glue Application records against ticket history; admins can apply or revert documentation changes',
      },
      {
        title: 'IT Glue — Configurations',
        href: '/analyzer/itglue/configurations',
        icon: Database,
        description: 'Audit IT Glue Configuration records (servers, workstations, devices) against ticket history; admins can apply or revert',
      },
    ],
  },
  {
    title: 'Admin',
    icon: Activity,
    children: [
      {
        title: 'Admin home',
        href: '/admin',
        icon: Activity,
        description: 'Tile index of every admin tool',
      },
      {
        title: 'Sync schedules',
        href: '/admin/sync',
        icon: GitCompare,
        description: 'Cron-driven syncs for Autotask, IT Glue, Veeam, Engagement, etc.',
      },
      {
        title: 'Workflow rules',
        href: '/admin/workflow',
        icon: Brain,
        description: 'Classification, AI prompts, ticket digest, and execution history',
      },
      {
        title: 'RMM Overshell',
        href: '/admin/rmm-overshell',
        icon: Activity,
        description: 'Curated Datto RMM scripts; recent executions and rate limits',
      },
      {
        title: 'IT Glue write log',
        href: '/admin/itglue-writes',
        icon: Database,
        description: 'Audit-driven changes pushed back to IT Glue; revert from here',
      },
      {
        title: 'Integrations',
        href: '/admin/integrations',
        icon: Activity,
        description: 'Toggle integrations on or off — affects /status without a container restart',
      },
      {
        title: 'Device-link conflicts',
        href: '/admin/device-link-conflicts',
        icon: AlertTriangle,
        description: 'Cross-system mappings needing a human decision',
      },
      {
        title: 'Users & roles',
        href: '/admin/users',
        icon: Users,
        description: 'Invite users, manage roles and permissions',
      },
    ],
  },
];

export function AppNavigation() {
  const pathname = usePathname();
  const { data: session } = useSession();
  const userRole = (session?.user as any)?.role || 'user';
  const isSuperAdmin = userRole === 'super-admin';

  // Mobile routes have their own nav — suppress desktop header
  if (pathname.startsWith('/mobile')) return null;

  const isActive = (href?: string) => {
    if (!href) return false;
    return pathname === href || pathname.startsWith(href + '/');
  };

  // Hide Engagement and Admin from non-super-admins
  const visibleItems = navigationItems.filter((item) => {
    if (item.title === 'Engagement' || item.title === 'Admin') {
      return isSuperAdmin;
    }
    return true;
  });

  return (
    <header className="sticky top-0 z-50 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
      <div className="container mx-auto px-6 flex h-16 items-center justify-between">
        {/* Mobile hamburger + brand */}
        <div className="flex items-center gap-2 shrink-0">
          <MobileNav items={visibleItems} pathname={pathname} isActive={isActive} />
          <Link href="/" className="flex items-center space-x-3">
            <img
              src="/wulff-logo.png"
              alt="Wulf Consulting"
              className="h-10 w-auto"
            />
            <div className="hidden sm:block">
              <h1 className="text-xl font-semibold tracking-tight">Pulse</h1>
              <p className="text-xs text-muted-foreground">Operations console</p>
            </div>
          </Link>
        </div>

        {/* Main Navigation — centered, desktop only */}
        <NavigationMenu className="hidden md:flex">
            <NavigationMenuList>
              {visibleItems.map((item) => {
                const childActive = item.children?.some((c) => isActive(c.href)) ?? false;
                const flatActive = isActive(item.href);
                // Brand-blue 2px underline marks active state — echoes the
                // PageHeader rule rather than filling the button with primary.
                const activeRule = 'relative after:absolute after:inset-x-2 after:bottom-0 after:h-[2px] after:bg-primary after:rounded-full';
                return (
                  <NavigationMenuItem key={item.title}>
                    {item.children ? (
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                          <button
                            className={cn(
                              navigationMenuTriggerStyle(),
                              'h-9 px-4 py-2 group',
                              childActive && cn(activeRule, 'text-foreground'),
                            )}
                          >
                            {item.icon && <item.icon className="w-4 h-4 mr-2" />}
                            {item.title}
                            <ChevronDown className="relative top-[1px] ml-1 h-3 w-3 transition duration-200 group-data-[state=open]:rotate-180" aria-hidden="true" />
                          </button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="start" className="p-2 min-w-[320px] max-w-[440px]">
                          {item.children.map((child) => {
                            const active = isActive(child.href);
                            return (
                              <DropdownMenuItem key={child.title} asChild className="p-0 focus:bg-transparent">
                                <Link
                                  href={child.href || '#'}
                                  className={cn(
                                    'flex w-full items-start gap-3 rounded-sm px-3 py-2 text-sm leading-none no-underline outline-none transition-colors cursor-pointer',
                                    'hover:bg-accent/40 focus:bg-accent/40',
                                    active && 'bg-primary/10 text-primary',
                                  )}
                                >
                                  {child.icon && (
                                    <child.icon
                                      className={cn(
                                        'w-4 h-4 mt-0.5 shrink-0',
                                        active ? 'text-primary' : 'text-muted-foreground',
                                      )}
                                    />
                                  )}
                                  <div className="min-w-0 flex-1">
                                    <div className={cn('font-medium leading-none', active && 'text-primary')}>
                                      {child.title}
                                    </div>
                                    {child.description && (
                                      <p className="mt-1 line-clamp-2 text-xs leading-snug text-muted-foreground">
                                        {child.description}
                                      </p>
                                    )}
                                  </div>
                                </Link>
                              </DropdownMenuItem>
                            );
                          })}
                        </DropdownMenuContent>
                      </DropdownMenu>
                    ) : (
                      <Link href={item.href || '#'} legacyBehavior passHref>
                        <NavigationMenuLink
                          className={cn(
                            navigationMenuTriggerStyle(),
                            'h-9',
                            flatActive && cn(activeRule, 'text-foreground'),
                          )}
                        >
                          {item.icon && <item.icon className="w-4 h-4 mr-2" />}
                          {item.title}
                        </NavigationMenuLink>
                      </Link>
                    )}
                  </NavigationMenuItem>
                );
              })}
            </NavigationMenuList>
        </NavigationMenu>

        {/* Right Side Actions */}
        <div className="flex items-center gap-1 shrink-0">
          <button
            type="button"
            onClick={() => document.dispatchEvent(new KeyboardEvent('keydown', { key: 'k', metaKey: true }))}
            className="hidden md:inline-flex h-9 items-center gap-2 rounded-md border bg-muted/40 px-2.5 text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
            aria-label="Open command palette"
          >
            <Search className="h-3.5 w-3.5" />
            <span className="hidden lg:inline">Search</span>
            <kbd className="num text-[10px] bg-background border rounded-sm px-1 py-px">⌘K</kbd>
          </button>
          <StatusIndicator />
          <ThemeToggle />
          <UserMenu />
        </div>
      </div>
    </header>
  );
}

// PageHeader moved to ./page-header.tsx; re-exported for backwards compatibility.
export { PageHeader } from '@/components/navigation/page-header';
export type { BreadcrumbItem, PageHeaderProps } from '@/components/navigation/page-header';
