import { useState } from "react";
import { Link, Outlet, useNavigate, useRouterState } from "@tanstack/react-router";
import {
  FileStack,
  HelpCircle,
  LayoutDashboard,
  LogOut,
  Menu,
  PanelLeftClose,
  Search,
  Upload,
  UserRound,
  type LucideIcon,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { logout } from "@/lib/auth";
import { useAuthSession } from "@/hooks/useAuthSession";
import { SIDEBAR_DEFAULT_WIDTH, useResizableSidebar } from "@/hooks/useResizableSidebar";
import { AmanahMark, AmanahWordmark } from "@/components/brand/AmanahMark";
import { UserAvatar } from "@/components/auth/UserAvatar";
import { NotificationBell } from "@/components/notifications/NotificationBell";
import { GlobalSearch } from "@/components/search/GlobalSearch";
import { Button } from "@/components/ui/button";

interface NavItem {
  to: string;
  label: string;
  icon: LucideIcon;
  exact?: boolean;
}

const GROUPS: { title: string; items: NavItem[] }[] = [
  {
    title: "Workspace",
    items: [
      { to: "/", label: "Dashboard", icon: LayoutDashboard, exact: true },
      { to: "/upload", label: "Send document", icon: Upload },
      { to: "/documents", label: "Documents", icon: FileStack },
      { to: "/queries", label: "Questions", icon: HelpCircle },
    ],
  },
  {
    title: "Account",
    items: [{ to: "/profile", label: "My account", icon: UserRound }],
  },
];

export function ClientShell({ children }: { children?: React.ReactNode }) {
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const navigate = useNavigate();
  const session = useAuthSession("client");
  const { collapsed, displayedWidth, resizing, setCollapsed, onResizePointerDown } =
    useResizableSidebar("client");
  const [drawer, setDrawer] = useState(false);

  const handleLogout = () => {
    logout("client");
    navigate({ to: "/login" });
  };

  const isActive = (item: NavItem) => {
    if (item.exact) return pathname === item.to;
    if (item.to === "/documents") {
      return pathname === "/documents" || pathname.startsWith("/documents/");
    }
    return pathname === item.to || pathname.startsWith(`${item.to}/`);
  };

  const crumb =
    GROUPS.flatMap((g) => g.items).find((i) => isActive(i))?.label ??
    (pathname.startsWith("/documents/")
      ? "Document"
      : pathname === "/notifications"
        ? "Notifications"
        : pathname === "/search"
          ? "Search"
          : "Client");

  const displayName = session?.name ?? "Client";
  const companyLabel = session?.company || "Your business";

  const sidebar = (
    <div className="flex h-full min-h-0 flex-col bg-[#F3F5F8]">
      <div
        className={cn(
          "flex shrink-0 items-center gap-3 border-b border-border/80 px-5 py-5",
          collapsed && "justify-center px-3",
        )}
      >
        <AmanahMark size={40} className="shadow-[0_1px_2px_rgba(40,56,80,0.16)]" />
        {!collapsed && <AmanahWordmark subtitle="Client workspace" />}
      </div>

      <div className="min-h-0 flex-1 overflow-y-auto px-3 py-4">
        <nav aria-label="Client navigation">
          {GROUPS.map((group, groupIndex) => (
            <div key={group.title} className={cn(groupIndex > 0 && "mt-7")}>
              {!collapsed && (
                <div className="mb-2.5 flex items-center gap-2 px-2">
                  <p className="text-[10px] font-bold tracking-[0.16em] text-muted-foreground uppercase">
                    {group.title}
                  </p>
                  <span className="h-px flex-1 bg-border/70" aria-hidden="true" />
                </div>
              )}
              <ul className="space-y-1">
                {group.items.map((item) => {
                  const active = isActive(item);
                  const Icon = item.icon;
                  return (
                    <li key={item.to}>
                      <Link
                        to={item.to}
                        onClick={() => setDrawer(false)}
                        aria-current={active ? "page" : undefined}
                        title={collapsed ? item.label : undefined}
                        className={cn(
                          "group relative flex min-h-10 items-center gap-3 rounded-xl px-3 text-[13px] transition-all duration-150",
                          active
                            ? "bg-primary font-semibold text-primary-foreground shadow-[0_1px_2px_rgba(40,56,80,0.14)]"
                            : "font-medium text-muted-foreground hover:bg-white/80 hover:text-foreground",
                          collapsed && "justify-center px-0",
                        )}
                      >
                        {active ? (
                          <span
                            className="absolute inset-y-2 left-0 w-[3px] rounded-full bg-brand"
                            aria-hidden="true"
                          />
                        ) : null}
                        <span
                          className={cn(
                            "flex size-8 shrink-0 items-center justify-center rounded-lg transition-colors",
                            active
                              ? "bg-white/15 text-primary-foreground"
                              : "bg-white/60 text-muted-foreground group-hover:bg-white group-hover:text-foreground",
                          )}
                        >
                          <Icon size={17} aria-hidden="true" />
                        </span>
                        {!collapsed && <span className="truncate">{item.label}</span>}
                      </Link>
                    </li>
                  );
                })}
              </ul>
            </div>
          ))}
        </nav>
      </div>

      <div className="mt-auto shrink-0 border-t border-border/80 bg-[#F3F5F8] px-3 py-3">
        <Link
          to="/profile"
          onClick={() => setDrawer(false)}
          className={cn(
            "flex items-center gap-3 rounded-xl border border-border/70 bg-white px-3 py-2.5 shadow-sm transition-colors hover:border-primary/30 hover:bg-primary-soft/40",
            collapsed && "justify-center border-0 bg-transparent px-0 shadow-none",
            pathname === "/profile" && "border-primary/30 bg-primary-soft/50",
          )}
          title={collapsed ? "My account" : undefined}
        >
          <span className="flex size-9 shrink-0 overflow-hidden rounded-full">
            <UserAvatar name={displayName} avatarUrl={session?.avatarUrl} size="md" className="size-9" />
          </span>
          {!collapsed && (
            <div className="min-w-0 flex-1">
              <p className="truncate text-[13px] font-semibold text-foreground">{displayName}</p>
              <p className="truncate text-[11px] text-muted-foreground">{companyLabel}</p>
            </div>
          )}
        </Link>
        {!collapsed && (
          <Button
            variant="ghost"
            size="sm"
            className="mt-2 w-full justify-start gap-2 text-[12px] text-muted-foreground"
            onClick={handleLogout}
          >
            <LogOut size={15} aria-hidden="true" />
            Sign out
          </Button>
        )}
      </div>
    </div>
  );

  return (
    <div
      className="min-h-screen w-full bg-background"
      style={{ ["--amanah-sidebar-width" as string]: `${displayedWidth}px` }}
    >
      <aside
        className={cn(
          "fixed inset-y-0 left-0 z-40 hidden overflow-hidden border-r border-border/80 bg-[#F3F5F8] shadow-[inset_-1px_0_0_rgba(213,219,229,0.5)] lg:block",
          resizing ? "transition-none" : "transition-[width] duration-150 ease-out",
        )}
        style={{ width: "var(--amanah-sidebar-width)" }}
      >
        {sidebar}
        <div
          role="separator"
          aria-orientation="vertical"
          aria-label="Resize sidebar"
          title="Drag to resize"
          tabIndex={0}
          onPointerDown={onResizePointerDown}
          className={cn(
            "absolute inset-y-0 right-0 z-20 w-2 cursor-col-resize touch-none",
            "after:absolute after:inset-y-0 after:right-0 after:w-px after:bg-transparent after:transition-colors",
            "hover:after:bg-primary/35",
            resizing && "after:bg-primary/50",
          )}
        />
      </aside>

      {drawer && (
        <div className="fixed inset-0 z-50 lg:hidden">
          <button
            className="absolute inset-0 bg-foreground/30"
            aria-label="Close navigation"
            onClick={() => setDrawer(false)}
          />
          <div
            className="absolute inset-y-0 left-0 border-r border-border/80 bg-[#F3F5F8] shadow-[inset_-1px_0_0_rgba(213,219,229,0.5)]"
            style={{ width: SIDEBAR_DEFAULT_WIDTH }}
          >
            {sidebar}
          </div>
        </div>
      )}

      <div className="flex min-h-screen min-w-0 flex-col overflow-x-clip lg:pl-[var(--amanah-sidebar-width)]">
        <header className="sticky top-0 z-30 flex h-14 items-center gap-3 border-b border-border bg-background/90 px-4 backdrop-blur md:px-8">
          <Button
            variant="ghost"
            size="icon"
            className="lg:hidden"
            aria-label="Open navigation"
            onClick={() => setDrawer(true)}
          >
            <Menu size={18} />
          </Button>
          <Button
            variant="ghost"
            size="icon"
            className="hidden lg:inline-flex"
            aria-label={collapsed ? "Expand sidebar" : "Collapse sidebar"}
            onClick={() => setCollapsed((c) => !c)}
          >
            <PanelLeftClose size={18} />
          </Button>
          <nav aria-label="Breadcrumb" className="min-w-0 text-[13px] text-muted-foreground">
            <ol className="flex items-center gap-1.5">
              <li>
                <Link to="/" className="hover:text-foreground">
                  Client
                </Link>
              </li>
              <li aria-hidden="true">/</li>
              <li className="truncate font-medium text-foreground">{crumb}</li>
            </ol>
          </nav>
          <div className="ml-auto flex min-w-0 items-center gap-3">
            <GlobalSearch platform="client" variant="header" className="hidden min-w-0 md:block" />
            <Button
              variant="ghost"
              size="icon"
              className="shrink-0 md:hidden"
              aria-label="Search"
              onClick={() => navigate({ to: "/search" })}
            >
              <Search size={18} />
            </Button>
            <NotificationBell platform="client" />
            <Link
              to="/profile"
              className="flex size-8 shrink-0 overflow-hidden rounded-full transition-opacity hover:opacity-90"
              title={`${displayName} · My account`}
              aria-label="Open my account"
            >
              <UserAvatar name={displayName} avatarUrl={session?.avatarUrl} size="sm" className="size-8" />
            </Link>
          </div>
        </header>
        <main className="min-w-0 flex-1 px-4 py-6 md:px-6 lg:px-8 lg:py-8">
          {children ?? <Outlet />}
        </main>
      </div>
    </div>
  );
}
