"use client";
import { useState, useRef } from "react";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import {
  Menu,
  Bell,
  ChevronDown,
  MoreHorizontal,
  LogOut,
  UserRound,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Sheet,
  SheetContent,
  SheetTitle,
  SheetDescription,
} from "@/components/ui/sheet";
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog";
import { ThemeToggle } from "./theme";
import { Brand } from "./brand";
import { navigation } from "./navigation";
import { cn } from "@/lib/utils";
import { canAccessFeature } from "@/lib/auth/feature-permissions";
import { postAuthRequest, type SafeAuthSession } from "@/features/auth/auth-client";
import { roles } from "@/features/auth/validation";
export function DashboardShell({
  children,
  session,
}: {
  children: React.ReactNode;
  session?: SafeAuthSession | null;
}) {
  const activeSession = session;
  const accountName = activeSession?.firstName || activeSession?.email.split("@")[0] || "Albert";
  const initials = activeSession
    ? `${activeSession.firstName?.trim().slice(0, 1) ?? ""}${activeSession.lastName?.trim().slice(0, 1) ?? ""}`.toUpperCase() || accountName.slice(0, 2).toUpperCase()
    : "AA";
  const roleLabel =
    roles.find((role) => role.value === activeSession?.role)?.label ||
    "Operator";
  const [signOutError, setSignOutError] = useState("");
  const [signingOut, setSigningOut] = useState(false);
  const signOutPending = useRef(false);
  const [collapsed, setCollapsed] = useState(false);
  const [hover, setHover] = useState(false);
  const [mobile, setMobile] = useState(false);
  const [controls, setControls] = useState(false);
  const [unavailable, setUnavailable] = useState("");
  const pathname = usePathname();
  const router = useRouter();
  const [openSections, setOpenSections] = useState<Record<string, boolean>>({});
  const visibleNavigation = navigation
    .map((group) => ({
      ...group,
      items: group.items.flatMap((item) => {
        if (item.feature && !canAccessFeature(activeSession?.role, item.feature)) return [];
        const children = item.children?.filter((child) =>
          typeof child === "string" || !child.feature ||
          canAccessFeature(activeSession?.role, child.feature),
        );
        if (item.children && !children?.length) return [];
        return [{ ...item, children }];
      }),
    }))
    .filter((group) => group.items.length > 0);
  const expanded = !collapsed || hover;
  async function signOut() {
    if (signOutPending.current) return;
    signOutPending.current = true;
    setSigningOut(true);
    setSignOutError("");
    const result = await postAuthRequest("/api/auth/logout");
    signOutPending.current = false;
    setSigningOut(false);
    if (!result.ok) {
      setSignOutError(result.error);
      return;
    }
    router.replace("/signin");
    router.refresh();
  }
  function nav(wide: boolean) {
    return (
      <nav aria-label="Main navigation" className="space-y-6">
        {visibleNavigation.map((group) => (
          <section key={group.label}>
            <h2
              className={cn(
                "mb-5 text-xs text-muted-foreground",
                !wide && "sr-only",
              )}
            >
              {group.label}
            </h2>
            <ul className="space-y-4">
              {group.items.map((item) => {
                const Icon = item.icon;
                const href = "href" in item ? item.href : undefined;
                const children = "children" in item ? item.children : undefined;
                const active =
                  href === "/"
                    ? pathname === "/"
                    : !!href && pathname.startsWith(href);
                const activeChild = children?.some(
                  (child) =>
                    typeof child !== "string" &&
                    pathname.startsWith(child.href ?? "\0"),
                );
                const submenuOpen = openSections[item.label] ?? !!activeChild;
                return (
                  <li key={item.label}>
                    {href ? (
                      <Link
                        href={href}
                        onClick={() => setMobile(false)}
                        aria-current={active ? "page" : undefined}
                        title={!wide ? item.label : undefined}
                        className={cn(
                          "flex min-h-10 items-center gap-3 rounded-lg px-3 py-2 font-medium",
                          active
                            ? "bg-sidebar-active text-sidebar-active-foreground"
                            : "hover:bg-muted",
                        )}
                      >
                        <Icon className="size-6 shrink-0 text-muted-foreground" />
                        <span className={!wide ? "sr-only" : ""}>
                          {item.label}
                        </span>
                      </Link>
                    ) : children && wide ? (
                      <details
                        className="group"
                        open={submenuOpen}
                        onToggle={(event) => {
                          const nextOpen = event.currentTarget.open;
                          setOpenSections((current) =>
                            current[item.label] === nextOpen
                              ? current
                              : { ...current, [item.label]: nextOpen },
                          );
                        }}
                      >
                        <summary className="flex min-h-10 cursor-pointer list-none items-center gap-3 rounded-lg px-3 py-2 font-medium hover:bg-muted">
                          <Icon className="size-6 shrink-0 text-muted-foreground" />
                          {item.label}
                          <ChevronDown className="ml-auto size-4 group-open:rotate-180" />
                        </summary>
                        <ul className="mt-2 ml-10 space-y-2">
                          {children.map((child) => {
                            const label =
                              typeof child === "string" ? child : child.label;
                            const childHref =
                              typeof child === "string" ? undefined : child.href;
                            const childActive =
                              !!childHref && pathname === childHref;
                            return (
                              <li key={label}>
                                {childHref ? (
                                  <Link
                                    href={childHref}
                                    onClick={() => setMobile(false)}
                                    aria-current={childActive ? "page" : undefined}
                                    className={cn(
                                      "block w-full rounded-md px-3 py-2 text-left",
                                      childActive
                                        ? "bg-sidebar-active text-sidebar-active-foreground"
                                        : "hover:bg-muted",
                                    )}
                                  >
                                    {label}
                                  </Link>
                                ) : (
                                  <button
                                    className="w-full rounded-md px-3 py-2 text-left hover:bg-muted"
                                    onClick={() => setUnavailable(label)}
                                  >
                                    {label}
                                  </button>
                                )}
                              </li>
                            );
                          })}
                        </ul>
                      </details>
                    ) : (
                      <button
                        title={!wide ? item.label : undefined}
                        className="flex min-h-10 w-full items-center gap-3 rounded-lg px-3 py-2 text-left font-medium hover:bg-muted"
                        onClick={() => setUnavailable(item.label)}
                      >
                        <Icon className="size-6 shrink-0 text-muted-foreground" />
                        <span className={!wide ? "sr-only" : ""}>
                          {item.label}
                        </span>
                      </button>
                    )}
                  </li>
                );
              })}
            </ul>
          </section>
        ))}
      </nav>
    );
  }
  const headerControls = (
    <div className="flex items-center gap-3">
      <ThemeToggle />
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            variant="outline"
            size="icon"
            className="relative rounded-full"
            aria-label="Notifications"
          >
            <Bell className="size-5" />
            <span className="absolute right-0.5 top-0.5 size-2 rounded-full bg-warning" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-80 p-4">
          <DropdownMenuLabel>Notifications</DropdownMenuLabel>
          <DropdownMenuSeparator />
          <p className="py-6 text-center text-muted-foreground">
            No new notifications
          </p>
        </DropdownMenuContent>
      </DropdownMenu>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <button
            className="flex items-center gap-3 rounded-lg px-1 py-2"
            aria-label={`${accountName} account menu`}
          >
            <span className="flex size-11 items-center justify-center rounded-full bg-info/10 font-semibold text-info">
              {initials}
            </span>
            <span className="max-w-40 truncate font-medium">{accountName}</span>
            <ChevronDown className="size-4" />
          </button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-56">
          <DropdownMenuLabel>
            <span className="block truncate">
              {[activeSession?.firstName, activeSession?.lastName].filter(Boolean).join(" ") || accountName}
            </span>
            {activeSession?.email && <span className="block truncate text-xs font-normal text-muted-foreground">{activeSession.email}</span>}
            <span className="text-xs font-normal text-muted-foreground">
              {roleLabel}{activeSession ? ` · ${activeSession.tenantCode}` : ""}
            </span>
          </DropdownMenuLabel>
          <DropdownMenuSeparator />
          {activeSession && (
            <DropdownMenuItem asChild>
              <Link href="/profile">
                <UserRound />
                Profile Settings
              </Link>
            </DropdownMenuItem>
          )}
          <DropdownMenuItem
            disabled={signingOut}
            onSelect={(event) => {
              event.preventDefault();
              void signOut();
            }}
          >
            <LogOut />
            {signingOut ? "Signing out..." : "Sign out"}
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  );
  return (
    <div>
      <a
        href="#main-content"
        className="fixed left-4 top-4 z-50 -translate-y-24 rounded-lg bg-card p-3 focus:translate-y-0"
      >
        Skip to main content
      </a>
      <aside
        onMouseEnter={() => setHover(true)}
        onMouseLeave={() => setHover(false)}
        className={cn(
          "fixed inset-y-0 left-0 z-40 hidden border-r bg-sidebar px-5 transition-[width] lg:block",
          expanded ? "w-[290px]" : "w-[90px]",
        )}
      >
        <Link href="/" className="flex h-28 items-center px-1">
          <Brand compact={!expanded} />
        </Link>
        <div className="h-[calc(100dvh-112px)] overflow-y-auto pb-6">
          {nav(expanded)}
        </div>
      </aside>
      <Sheet open={mobile} onOpenChange={setMobile}>
        <SheetContent
          side="left"
          className="w-[290px] gap-0 overflow-y-auto bg-sidebar px-5"
        >
          <SheetTitle className="sr-only">Navigation</SheetTitle>
          <SheetDescription className="sr-only">
            Operator dashboard navigation
          </SheetDescription>
          <Link
            href="/"
            onClick={() => setMobile(false)}
            className="flex h-28 items-center"
          >
            <Brand />
          </Link>
          {nav(true)}
        </SheetContent>
      </Sheet>
      <div
        className={cn(
          "min-w-0 transition-[margin]",
          collapsed ? "lg:ml-[90px]" : "lg:ml-[290px]",
        )}
      >
        <header className="sticky top-0 z-30 border-b bg-card">
          <div className="flex h-[76px] items-center justify-between gap-4 px-4 md:px-6">
            <Button
              variant="outline"
              size="icon"
              aria-label="Toggle sidebar"
              className="hidden lg:inline-flex"
              onClick={() => setCollapsed(!collapsed)}
            >
              <Menu className="size-5" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              aria-label="Open navigation"
              className="lg:hidden"
              onClick={() => setMobile(true)}
            >
              <Menu className="size-6" />
            </Button>
            <Link href="/" className="lg:hidden">
              <Brand />
            </Link>
            <div className="hidden lg:block">{headerControls}</div>
            <Button
              variant="ghost"
              size="icon"
              aria-label="Show header controls"
              className="lg:hidden"
              onClick={() => setControls(!controls)}
              aria-expanded={controls}
            >
              <MoreHorizontal />
            </Button>
          </div>
          {controls && (
            <div className="flex justify-end border-t px-4 py-3 lg:hidden">
              {headerControls}
            </div>
          )}
        </header>
        <main
          id="main-content"
          className="mx-auto max-w-[1536px] min-w-0 p-4 md:p-6"
        >
          {children}
        </main>
      </div>
      <Dialog
        open={!!signOutError}
        onOpenChange={(open) => {
          if (!open) setSignOutError("");
        }}
      >
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Could not sign out</DialogTitle>
            <DialogDescription>{signOutError}</DialogDescription>
          </DialogHeader>
          <Button onClick={() => void signOut()} disabled={signingOut}>
            {signingOut ? "Signing out..." : "Try again"}
          </Button>
        </DialogContent>
      </Dialog>
      <Dialog
        open={!!unavailable}
        onOpenChange={(open) => {
          if (!open) setUnavailable("");
        }}
      >
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>{unavailable}</DialogTitle>
            <DialogDescription>
              This area will be reconstructed in a later phase.
            </DialogDescription>
          </DialogHeader>
          <Button onClick={() => setUnavailable("")}>Close</Button>
        </DialogContent>
      </Dialog>
    </div>
  );
}
