import React from "react";
import { Link, useLocation } from "react-router-dom";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
  NavigationMenu,
  NavigationMenuContent,
  NavigationMenuItem,
  NavigationMenuLink,
  NavigationMenuList,
  NavigationMenuTrigger,
} from "@/components/ui/navigation-menu";
import {
  Command,
  FileCode,
  BookOpen,
  Code2,
  Package,
  LayoutTemplate,
  Store,
  User,
  Menu,
  X,
  Zap,
  FlaskConical,
  LayoutDashboard,
  ChevronRight,
} from "lucide-react";

export interface DevPlatformNavProps {
  className?: string;
}

interface NavEntry {
  name: string;
  href: string;
  icon: React.ElementType;
  description: string;
  comingSoon?: boolean;
}

interface NavGroup {
  label: string;
  items: NavEntry[];
}

// ── Grouped nav structure ──────────────────────────────────────────────────────
const NAV_GROUPS: NavGroup[] = [
  {
    label: "Learn",
    items: [
      {
        name: "Quick Start",
        href: "/dev-platform/quick-start",
        icon: Zap,
        description: "Up and running in under 5 minutes",
      },
      {
        name: "Documentation",
        href: "/docs",
        icon: BookOpen,
        description: "Guides, concepts, and deep dives",
      },
      {
        name: "Code Examples",
        href: "/dev-platform/examples",
        icon: FlaskConical,
        description: "Copy-paste snippets for common patterns",
      },
    ],
  },
  {
    label: "Build",
    items: [
      {
        name: "API Reference",
        href: "/dev-platform/api-reference",
        icon: Code2,
        description: "Full endpoint docs with live samples",
      },
      {
        name: "SDK",
        href: "/sdk",
        icon: Package,
        description: "Client libraries for JS, Python, Go and more",
        comingSoon: true,
      },
      {
        name: "Templates",
        href: "/dev-platform/templates",
        icon: LayoutTemplate,
        description: "Project starters and boilerplates",
      },
      {
        name: "Marketplace",
        href: "/dev-platform/marketplace",
        icon: Store,
        description: "Plugins, integrations, and extensions",
        comingSoon: true,
      },
    ],
  },
];

// ── Shared dropdown item component ────────────────────────────────────────────
function DropdownItem({ item, onClick }: { item: NavEntry; onClick?: () => void }) {
  return (
    <NavigationMenuLink asChild>
      <Link
        to={item.href}
        onClick={onClick}
        className="group flex select-none gap-3 rounded-md p-3 leading-none no-underline outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground"
      >
        <div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border/60 bg-muted/50 group-hover:border-primary/30 group-hover:bg-primary/10 transition-colors">
          <item.icon className="h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors" />
        </div>
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2">
            <span className="text-sm font-medium leading-none">{item.name}</span>
            {item.comingSoon && (
              <span className="rounded-full bg-primary/15 px-1.5 py-0.5 text-[10px] font-medium text-primary leading-none">
                Soon
              </span>
            )}
          </div>
          <p className="mt-1 text-xs leading-snug text-muted-foreground line-clamp-2">
            {item.description}
          </p>
        </div>
      </Link>
    </NavigationMenuLink>
  );
}

export function DevPlatformNav({ className }: DevPlatformNavProps) {
  const [mobileMenuOpen, setMobileMenuOpen] = React.useState(false);
  const [searchOpen, setSearchOpen] = React.useState(false);
  const location = useLocation();

  React.useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "k") {
        e.preventDefault();
        setSearchOpen(true);
      }
    };
    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, []);

  const isGroupActive = (group: NavGroup) =>
    group.items.some((item) => location.pathname.startsWith(item.href));

  return (
    <nav
      className={cn(
        "sticky top-0 z-50 w-full border-b border-border/40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60",
        className
      )}
    >
      <div className="container flex h-16 items-center">
        {/* Logo */}
        <Link
          to="/dev-platform"
          className="mr-8 flex items-center space-x-2 transition-opacity hover:opacity-80"
        >
          <FileCode className="h-6 w-6 text-primary" />
          <span className="font-bold text-lg">
            aethex<span className="text-primary">.dev</span>
          </span>
        </Link>

        {/* Desktop Navigation */}
        <div className="hidden md:flex md:flex-1 md:items-center md:justify-between">
          <NavigationMenu>
            <NavigationMenuList>
              {NAV_GROUPS.map((group) => (
                <NavigationMenuItem key={group.label}>
                  <NavigationMenuTrigger
                    className={cn(
                      "h-10 text-sm font-medium",
                      isGroupActive(group) && "text-primary"
                    )}
                  >
                    {group.label}
                  </NavigationMenuTrigger>
                  <NavigationMenuContent>
                    <ul className="grid w-[420px] gap-1 p-3">
                      {/* Group header */}
                      <li className="px-2 pb-1">
                        <p className="text-[10px] font-semibold uppercase tracking-widest text-muted-foreground/60">
                          {group.label}
                        </p>
                      </li>
                      {group.items.map((item) => (
                        <li key={item.href}>
                          <DropdownItem item={item} />
                        </li>
                      ))}
                    </ul>
                  </NavigationMenuContent>
                </NavigationMenuItem>
              ))}

              {/* Standalone Dashboard link */}
              <NavigationMenuItem>
                <NavigationMenuLink asChild>
                  <Link
                    to="/dev-platform/dashboard"
                    className={cn(
                      "group inline-flex h-10 items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:outline-none",
                      location.pathname.startsWith("/dev-platform/dashboard") &&
                        "bg-accent text-accent-foreground"
                    )}
                  >
                    <LayoutDashboard className="mr-2 h-4 w-4" />
                    Dashboard
                  </Link>
                </NavigationMenuLink>
              </NavigationMenuItem>
            </NavigationMenuList>
          </NavigationMenu>

          {/* Right side actions */}
          <div className="flex items-center space-x-3">
            <Button
              variant="outline"
              size="sm"
              className="relative h-9 justify-start text-sm text-muted-foreground w-48"
              onClick={() => setSearchOpen(true)}
            >
              <Command className="mr-2 h-4 w-4 shrink-0" />
              <span>Search docs...</span>
              <kbd className="pointer-events-none absolute right-2 hidden h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium sm:flex">
                <span className="text-xs">⌘</span>K
              </kbd>
            </Button>

            <Link to="/profile">
              <Button variant="ghost" size="icon" className="h-9 w-9">
                <User className="h-4 w-4" />
              </Button>
            </Link>
          </div>
        </div>

        {/* Mobile menu button */}
        <div className="flex flex-1 items-center justify-end md:hidden">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
          >
            {mobileMenuOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
          </Button>
        </div>
      </div>

      {/* Mobile Navigation */}
      {mobileMenuOpen && (
        <div className="border-t border-border/40 md:hidden">
          <div className="container py-4 space-y-4">
            {NAV_GROUPS.map((group) => (
              <div key={group.label}>
                <p className="px-3 pb-1 text-[10px] font-semibold uppercase tracking-widest text-muted-foreground/60">
                  {group.label}
                </p>
                {group.items.map((item) => (
                  <Link
                    key={item.href}
                    to={item.href}
                    onClick={() => setMobileMenuOpen(false)}
                    className={cn(
                      "flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground",
                      location.pathname.startsWith(item.href) && "bg-accent text-accent-foreground"
                    )}
                  >
                    <item.icon className="h-4 w-4 shrink-0" />
                    <span className="flex-1">{item.name}</span>
                    {item.comingSoon && (
                      <span className="rounded-full bg-primary/15 px-1.5 py-0.5 text-[10px] font-medium text-primary">
                        Soon
                      </span>
                    )}
                    <ChevronRight className="h-3 w-3 text-muted-foreground/50" />
                  </Link>
                ))}
              </div>
            ))}

            <div className="border-t border-border/40 pt-3">
              <Link
                to="/dev-platform/dashboard"
                onClick={() => setMobileMenuOpen(false)}
                className="flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground"
              >
                <LayoutDashboard className="h-4 w-4" />
                Dashboard
              </Link>
              <Link
                to="/profile"
                onClick={() => setMobileMenuOpen(false)}
                className="flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground"
              >
                <User className="h-4 w-4" />
                Profile
              </Link>
            </div>
          </div>
        </div>
      )}

      {/* Command Palette */}
      {searchOpen && (
        <div
          className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm"
          onClick={() => setSearchOpen(false)}
        >
          <div
            className="fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="rounded-xl border bg-background p-8 shadow-2xl min-w-80 text-center space-y-2">
              <Command className="mx-auto h-8 w-8 text-muted-foreground" />
              <p className="text-muted-foreground font-medium">Command palette coming soon</p>
              <p className="text-sm text-muted-foreground/60">Press Esc or click outside to close</p>
            </div>
          </div>
        </div>
      )}
    </nav>
  );
}
