import { useState, useRef, useEffect } from "react";
import { Link, router, usePage } from "@inertiajs/react";
import { Menu, X, ChevronDown, LayoutDashboard, LogOut, User as UserIcon } from "lucide-react";
import { useTenant } from "@/contexts/TenantContext";
import { useTenantHref } from "@/hooks/useTenantLink";
import { useAuth } from "@/hooks/useAuth";
import {
  DropdownMenu as ShadDropdown,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";

interface NavItem {
  label: string;
  href: string;
  children?: { label: string; href: string }[];
}

const navLinks: NavItem[] = [
  { label: "Home", href: "/" },
  {
    label: "Training Courses",
    href: "/courses",
    children: [
      { label: "All Courses", href: "/courses" },
      { label: "Plant Machinery", href: "/courses?cat=plant-machinery" },
      { label: "Traffic Management", href: "/courses?cat=traffic-management" },
      { label: "Health & Safety", href: "/courses?cat=health-safety" },
    ],
  },
  {
    label: "Smart Awards",
    href: "/courses?cat=smart-awards",
    children: [
      { label: "All Smart Awards", href: "/courses?cat=smart-awards" },
      { label: "Fibre Optics", href: "/courses?cat=fibre-optics" },
      { label: "Telecoms Safety", href: "/courses?cat=telecoms-safety" },
    ],
  },
  {
    label: "NRSWA Courses",
    href: "/courses?cat=nrswa",
    children: [
      { label: "All NRSWA Courses", href: "/courses?cat=nrswa" },
      { label: "Operative", href: "/courses?cat=nrswa-operative" },
      { label: "Supervisor", href: "/courses?cat=nrswa-supervisor" },
    ],
  },
  {
    label: "E-Learning",
    href: "/courses?cat=e-learning",
  },
  { label: "About", href: "/about" },
  { label: "Contact", href: "/contact" },
];

const DropdownMenu = ({ item, tenantHref, isActive, onNavigate }: {
  item: NavItem;
  tenantHref: (p: string) => string;
  isActive: (h: string) => boolean;
  onNavigate?: () => void;
}) => {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  return (
    <div ref={ref} className="relative">
      <button
        onClick={() => setOpen(!open)}
        className={`flex items-center gap-1 text-sm transition-colors ${
          isActive(item.href) ? "text-primary font-medium" : "text-muted-foreground hover:text-foreground"
        }`}
      >
        {item.label}
        <ChevronDown className={`h-3.5 w-3.5 transition-transform ${open ? "rotate-180" : ""}`} />
      </button>
      {open && (
        <div className="absolute top-full left-0 mt-2 w-56 bg-background border border-border rounded-md shadow-lg py-1 z-50">
          {item.children!.map((child) => (
            <Link
              key={child.label}
              href={tenantHref(child.href)}
              className="block px-4 py-2 text-sm text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
              onClick={() => { setOpen(false); onNavigate?.(); }}
            >
              {child.label}
            </Link>
          ))}
        </div>
      )}
    </div>
  );
};

const LocktelNavbar = () => {
  const [mobileOpen, setMobileOpen] = useState(false);
  const { url } = usePage();
  const pathname = url.split("?")[0];
  const { branding, companyName } = useTenant();
  const tenantHref = useTenantHref();
  const { user, signOut } = useAuth();
  const landingRoute = user?.landing_route ?? "/admin";
  const displayName = user?.full_name?.split(" ")[0] || user?.name || user?.email?.split("@")[0];

  const isActive = (href: string) => {
    const path = href.split("?")[0];
    return pathname === path || (path !== "/" && pathname.startsWith(path));
  };

  return (
    <nav className="fixed top-0 left-0 right-0 z-50 bg-background/95 backdrop-blur-md border-b border-border">
      <div className="container mx-auto flex items-center justify-between h-16 px-4">
        <Link href={tenantHref("/")} className="flex items-center gap-3">
          {branding?.logo_url ? (
            <img src={branding.logo_url} alt={companyName || "Locktel Academy"} className="h-10 object-contain" />
          ) : (
            <div className="font-bold text-xl text-foreground">{companyName || "Locktel Academy"}</div>
          )}
        </Link>

        {/* Desktop */}
        <div className="hidden lg:flex items-center gap-6">
          {navLinks.map((link) =>
            link.children ? (
              <DropdownMenu key={link.label} item={link} tenantHref={tenantHref} isActive={isActive} />
            ) : (
              <Link
                key={link.label}
                href={tenantHref(link.href)}
                className={`text-sm transition-colors ${
                  isActive(link.href) ? "text-primary font-medium" : "text-muted-foreground hover:text-foreground"
                }`}
              >
                {link.label}
              </Link>
            )
          )}
        </div>

        <div className="hidden lg:flex items-center gap-3">
          {user ? (
            <ShadDropdown>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" size="sm" className="gap-2">
                  <UserIcon className="w-4 h-4" />
                  <span className="max-w-[120px] truncate">{displayName}</span>
                  <ChevronDown className="w-3.5 h-3.5" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end" className="w-56">
                <DropdownMenuLabel className="text-xs">
                  <div className="font-medium text-foreground truncate">{user.full_name || user.name}</div>
                  <div className="text-muted-foreground truncate font-normal">{user.email}</div>
                </DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={() => router.visit(landingRoute)} className="gap-2">
                  <LayoutDashboard className="w-4 h-4" /> Dashboard
                </DropdownMenuItem>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={signOut} className="gap-2 text-destructive">
                  <LogOut className="w-4 h-4" /> Sign Out
                </DropdownMenuItem>
              </DropdownMenuContent>
            </ShadDropdown>
          ) : (
            <>
              <Link href="/login" className="text-sm text-muted-foreground hover:text-foreground transition-colors">
                Login
              </Link>
              <Link href="/register" className="text-sm bg-primary text-primary-foreground px-4 py-2 rounded-md hover:bg-primary/90 transition-colors">
                Register
              </Link>
            </>
          )}
        </div>

        {/* Mobile toggle */}
        <button className="lg:hidden text-foreground" onClick={() => setMobileOpen(!mobileOpen)}>
          {mobileOpen ? <X className="w-6 h-6" /> : <Menu className="w-6 h-6" />}
        </button>
      </div>

      {mobileOpen && (
        <div className="lg:hidden bg-background border-t border-border px-4 py-4 space-y-1 max-h-[70vh] overflow-y-auto">
          {navLinks.map((link) =>
            link.children ? (
              <div key={link.label}>
                <div className="text-sm font-medium text-foreground py-2">{link.label}</div>
                {link.children.map((child) => (
                  <Link
                    key={child.label}
                    href={tenantHref(child.href)}
                    className="block text-sm text-muted-foreground hover:text-foreground py-1.5 pl-4"
                    onClick={() => setMobileOpen(false)}
                  >
                    {child.label}
                  </Link>
                ))}
              </div>
            ) : (
              <Link
                key={link.label}
                href={tenantHref(link.href)}
                className={`block text-sm py-2 transition-colors ${
                  isActive(link.href) ? "text-primary font-medium" : "text-muted-foreground hover:text-foreground"
                }`}
                onClick={() => setMobileOpen(false)}
              >
                {link.label}
              </Link>
            )
          )}
          <div className="border-t border-border pt-3 mt-3 flex gap-3">
            {user ? (
              <>
                <button
                  className="text-sm text-muted-foreground hover:text-foreground"
                  onClick={() => { setMobileOpen(false); router.visit(landingRoute); }}
                >
                  Dashboard
                </button>
                <button
                  className="text-sm text-destructive"
                  onClick={() => { setMobileOpen(false); signOut(); }}
                >
                  Sign Out
                </button>
              </>
            ) : (
              <>
                <Link href="/login" className="text-sm text-muted-foreground hover:text-foreground" onClick={() => setMobileOpen(false)}>
                  Login
                </Link>
                <Link href="/register" className="text-sm bg-primary text-primary-foreground px-4 py-1.5 rounded-md" onClick={() => setMobileOpen(false)}>
                  Register
                </Link>
              </>
            )}
          </div>
        </div>
      )}
    </nav>
  );
};

export default LocktelNavbar;
