import { Link, useNavigate, useRouterState } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  Bell,
  ChevronsLeft,
  ChevronsRight,
  ChevronsUpDown,
  ListTodo,
  LogOut,
  Menu,
  Monitor,
  Moon,
  Search,
  Sun,
  UserCog,
  UserRound,
  WifiOff,
} from "lucide-react";
import { useEffect, useState, type ReactNode } from "react";
import { Wordmark } from "./brand";
import { DeveloperFooter } from "./developer-footer";
import { navFor, type NavGroup } from "./nav";
import { Button } from "@/components/ui/button";
import {
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import { globalSearch, listNotifications, unreadCount } from "@/api/ops";
import { getProviderDashboard } from "@/api/programme";
import type { RoleCode } from "@/api/types";
import { useAccess, useCan, useTheme } from "@/lib/access";
import { relativeTime } from "@/lib/format";
import { homePathFor, isTpRole, ROLE_LABELS } from "@/lib/roles";
import { listProjects } from "@/api/admin";
import { getAccess } from "@/api/auth";
import { setProjectId } from "@/api/http";
import { cn } from "@/lib/utils";

function NavLinks({
  groups,
  pid,
  collapsed,
  onNavigate,
}: {
  groups: NavGroup[];
  pid: string;
  collapsed: boolean;
  onNavigate?: () => void;
}) {
  const { access } = useAccess();
  return (
    <nav className="flex-1 space-y-5 overflow-y-auto px-3 py-4" aria-label="Main">
      {groups.map((g) => {
        const items = g.items.filter((i) => !i.perm || access?.permissions.includes(i.perm));
        if (!items.length) return null;
        return (
          <div key={g.label}>
            {!collapsed && (
              <p className="mb-1.5 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
                {g.label}
              </p>
            )}
            <ul className="space-y-0.5">
              {items.map((i) => (
                <li key={i.label}>
                  <Link
                    to={i.to}
                    params={{ pid }}
                    onClick={onNavigate}
                    title={collapsed ? i.label : undefined}
                    className={cn(
                      "flex items-center gap-2.5 rounded-md px-2 py-1.5 text-[13.5px] text-sidebar-foreground/85 transition-colors hover:bg-sidebar-accent",
                      collapsed && "justify-center",
                    )}
                    activeOptions={{ exact: !!i.exact }}
                    activeProps={{
                      className:
                        "bg-primary !text-primary-foreground hover:bg-primary-hover font-medium",
                    }}
                  >
                    <i.icon className="h-4 w-4 shrink-0" aria-hidden="true" />
                    {!collapsed && <span className="truncate">{i.label}</span>}
                  </Link>
                </li>
              ))}
            </ul>
          </div>
        );
      })}
    </nav>
  );
}

function GlobalSearch({ pid }: { pid: string }) {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState("");
  const navigate = useNavigate();
  useEffect(() => {
    const h = (e: KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        setOpen((o) => !o);
      }
    };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, []);
  const res = useQuery({
    queryKey: ["search", q],
    queryFn: () => globalSearch(q),
    enabled: q.trim().length >= 2,
  });
  const go = (fn: () => void) => {
    setOpen(false);
    setQ("");
    fn();
  };
  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className="flex h-9 w-full max-w-sm items-center gap-2 rounded-md border bg-card px-3 text-[13px] text-muted-foreground hover:border-primary/40"
      >
        <Search className="h-4 w-4" />
        <span className="flex-1 truncate text-left">Search trainees, providers, classes…</span>
        <kbd className="hidden rounded bg-surface-2 px-1.5 font-mono text-[11px] sm:inline">
          Ctrl K
        </kbd>
      </button>
      <CommandDialog open={open} onOpenChange={setOpen}>
        <CommandInput
          placeholder="Name, ID, phone, class code, GRM reference…"
          value={q}
          onValueChange={setQ}
        />
        <CommandList>
          <CommandEmpty>
            {q.length < 2
              ? "Type at least 2 characters."
              : res.isFetching
                ? "Searching…"
                : "No matches."}
          </CommandEmpty>
          {!!res.data?.trainees.length && (
            <CommandGroup heading="Trainees">
              {res.data.trainees.map((t) => (
                <CommandItem
                  key={t.id}
                  value={`t-${t.id}-${t.fullName}`}
                  onSelect={() =>
                    go(
                      () =>
                        void navigate({ to: "/p/$pid/trainees/$id", params: { pid, id: t.id } }),
                    )
                  }
                >
                  {t.fullName}
                  <span className="ml-auto font-mono text-[11px] text-muted-foreground">
                    {t.code}
                  </span>
                </CommandItem>
              ))}
            </CommandGroup>
          )}
          {!!res.data?.providers.length && (
            <CommandGroup heading="Providers">
              {res.data.providers.map((p) => (
                <CommandItem
                  key={p.id}
                  value={`p-${p.id}-${p.name}`}
                  onSelect={() =>
                    go(
                      () =>
                        void navigate({ to: "/p/$pid/providers/$id", params: { pid, id: p.id } }),
                    )
                  }
                >
                  {p.name}
                  <span className="ml-auto font-mono text-[11px]">{p.code}</span>
                </CommandItem>
              ))}
            </CommandGroup>
          )}
          {!!res.data?.classes.length && (
            <CommandGroup heading="Classes">
              {res.data.classes.map((c) => (
                <CommandItem
                  key={c.id}
                  value={`c-${c.id}-${c.code}`}
                  onSelect={() =>
                    go(
                      () => void navigate({ to: "/p/$pid/classes/$id", params: { pid, id: c.id } }),
                    )
                  }
                >
                  {c.code} · {c.trainingTitle}
                </CommandItem>
              ))}
            </CommandGroup>
          )}
          {!!res.data?.grievances.length && (
            <CommandGroup heading="Grievances">
              {res.data.grievances.map((g) => (
                <CommandItem
                  key={g.id}
                  value={`g-${g.id}-${g.ref}`}
                  onSelect={() =>
                    go(
                      () =>
                        void navigate({ to: "/p/$pid/grievances/$id", params: { pid, id: g.id } }),
                    )
                  }
                >
                  {g.ref} · {g.subject}
                </CommandItem>
              ))}
            </CommandGroup>
          )}
        </CommandList>
      </CommandDialog>
    </>
  );
}

function NotificationBell({ pid }: { pid: string }) {
  const count = useQuery({
    queryKey: ["notifications", "count"],
    queryFn: unreadCount,
    refetchInterval: 60000,
  });
  const list = useQuery({ queryKey: ["notifications"], queryFn: listNotifications });
  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button
          variant="ghost"
          size="icon"
          className="relative"
          aria-label={`Notifications${count.data ? `, ${count.data} unread` : ""}`}
        >
          <Bell className="h-5 w-5" />
          {!!count.data && (
            <span className="absolute right-1 top-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-danger px-1 text-[10px] font-bold text-primary-foreground">
              {count.data}
            </span>
          )}
        </Button>
      </PopoverTrigger>
      <PopoverContent align="end" className="w-80 p-0">
        <div className="border-b px-4 py-2.5 font-display font-semibold">Notifications</div>
        <ul className="max-h-80 overflow-y-auto">
          {(list.data ?? []).slice(0, 10).map((n) => (
            <li
              key={n.id}
              className={cn("border-b px-4 py-2.5 text-[13px]", !n.readAt && "bg-primary-soft/50")}
            >
              <p className="font-medium">{n.title}</p>
              {n.body && <p className="text-muted-foreground">{n.body}</p>}
              <p className="text-[11px] text-subtle">{relativeTime(n.createdAt)}</p>
            </li>
          ))}
        </ul>
        <Link
          to="/p/$pid/notifications"
          params={{ pid }}
          className="block px-4 py-2.5 text-center text-[13px] font-medium text-primary hover:underline"
        >
          View all
        </Link>
      </PopoverContent>
    </Popover>
  );
}

function WhatsDueButton({ pid, providerId }: { pid: string; providerId: string }) {
  const q = useQuery({
    queryKey: ["dashboard", "provider", providerId],
    queryFn: () => getProviderDashboard(providerId),
    staleTime: 60000,
  });
  const n =
    q.data?.todo.filter((t) => t.severity === "overdue" || t.severity === "due_soon").length ?? 0;
  return (
    <Button asChild variant="outline" size="sm" className="hidden md:inline-flex">
      <Link to="/p/$pid/home" params={{ pid }}>
        <ListTodo /> What's due
        {n > 0 && (
          <span className="rounded-full bg-amber px-1.5 text-[11px] font-bold text-foreground">
            {n}
          </span>
        )}
      </Link>
    </Button>
  );
}

function UserMenu({ pid }: { pid: string }) {
  const { access, refresh, signOut } = useAccess();
  const qc = useQueryClient();
  const { theme, setTheme } = useTheme();
  const navigate = useNavigate();
  if (!access) return null;
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <button
          type="button"
          className="flex items-center gap-2 rounded-md px-1.5 py-1 hover:bg-surface-2"
          aria-label="User menu"
        >
          <span className="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-[12px] font-bold text-primary-foreground">
            {access.userName
              .split(" ")
              .map((p) => p[0])
              .join("")}
          </span>
          <span className="hidden text-left leading-tight lg:block">
            <span className="block text-[13px] font-semibold">{access.userName}</span>
            <span className="block text-[11px] text-muted-foreground">{access.roleLabel}</span>
          </span>
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-60">
        <DropdownMenuLabel>{access.email}</DropdownMenuLabel>
        <DropdownMenuItem onSelect={() => void navigate({ to: "/p/$pid/me", params: { pid } })}>
          <UserRound /> Profile
        </DropdownMenuItem>
        <DropdownMenuSub>
          <DropdownMenuSubTrigger>
            <Sun className="mr-2 h-4 w-4" /> Theme
          </DropdownMenuSubTrigger>
          <DropdownMenuSubContent>
            <DropdownMenuRadioGroup
              value={theme}
              onValueChange={(v) => setTheme(v as typeof theme)}
            >
              <DropdownMenuRadioItem value="light">
                <Sun className="mr-2 h-4 w-4" />
                Light
              </DropdownMenuRadioItem>
              <DropdownMenuRadioItem value="dark">
                <Moon className="mr-2 h-4 w-4" />
                Dark
              </DropdownMenuRadioItem>
              <DropdownMenuRadioItem value="system">
                <Monitor className="mr-2 h-4 w-4" />
                System
              </DropdownMenuRadioItem>
            </DropdownMenuRadioGroup>
          </DropdownMenuSubContent>
        </DropdownMenuSub>
        <DropdownMenuSeparator />
        <DropdownMenuItem
          onSelect={() => {
            void signOut().then(() => navigate({ to: "/login" }));
          }}
        >
          <LogOut /> Sign out
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

/** The project in use. With several projects (or as an administrator) it opens the list of projects. */
function ProjectSwitcher({
  pid,
  providerName,
}: {
  pid: string;
  providerName?: string | undefined;
}) {
  const navigate = useNavigate();
  const q = useQuery({ queryKey: ["projects"], queryFn: listProjects, staleTime: 5 * 60_000 });
  const now = q.data?.find((p) => p.id === pid);
  const text = (
    <span className="min-w-0 flex-1 text-left">
      <span className="block font-semibold">{now?.code ?? "…"}</span>
      <span className="block truncate text-muted-foreground">{providerName ?? now?.title}</span>
    </span>
  );
  const box = "flex w-full items-center gap-2 rounded-md border bg-card px-3 py-2 text-[12px]";
  if (!q.data || (q.data.length < 2 && now?.roleCode !== "system_admin"))
    return <div className={box}>{text}</div>;
  const go = async (id: string) => {
    if (id === pid) return;
    setProjectId(id);
    const a = await getAccess();
    void navigate({
      to: `/p/$pid/${homePathFor(a.roleCode)}` as "/p/$pid/home",
      params: { pid: id },
    });
  };
  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <button
          type="button"
          aria-label="Change project"
          className={cn(box, "hover:border-primary")}
        >
          {text}
          <ChevronsUpDown className="h-4 w-4 shrink-0 text-subtle" aria-hidden />
        </button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="start" className="w-64">
        <DropdownMenuLabel>Projects</DropdownMenuLabel>
        {q.data.map((p) => (
          <DropdownMenuItem key={p.id} onSelect={() => void go(p.id)}>
            <span className="min-w-0">
              <span className="block font-medium">
                {p.code}
                {p.id === pid && " (open)"}
              </span>
              <span className="block truncate text-[12px] text-muted-foreground">{p.title}</span>
            </span>
          </DropdownMenuItem>
        ))}
        <DropdownMenuSeparator />
        <DropdownMenuItem onSelect={() => void navigate({ to: "/projects" })}>
          All projects{now?.roleCode === "system_admin" ? " and new project" : ""}
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}

function OfflineBanner() {
  const [off, setOff] = useState(false);
  useEffect(() => {
    const u = () => setOff(!navigator.onLine);
    u();
    window.addEventListener("online", u);
    window.addEventListener("offline", u);
    return () => {
      window.removeEventListener("online", u);
      window.removeEventListener("offline", u);
    };
  }, []);
  if (!off) return null;
  return (
    <div
      className="flex items-center justify-center gap-2 bg-warning px-4 py-1.5 text-[13px] font-medium text-primary-foreground"
      role="alert"
    >
      <WifiOff className="h-4 w-4" /> You are offline — changes will not be saved
    </div>
  );
}

export function AppShell({ pid, children }: { pid: string; children: ReactNode }) {
  const { access } = useAccess();
  const [collapsed, setCollapsed] = useState(false);
  const [mobile, setMobile] = useState(false);
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  useEffect(() => setMobile(false), [pathname]);
  const canTp = useCan("project.view") && !!access && isTpRole(access.roleCode);
  if (!access) return null;
  const groups = navFor(access.roleCode);
  const providerName = access.providerName;
  return (
    <div className="flex min-h-screen">
      <aside
        className={cn(
          "sticky top-0 hidden h-screen shrink-0 flex-col border-r bg-sidebar transition-[width] duration-200 lg:flex",
          collapsed ? "w-16" : "w-60",
        )}
      >
        <div className="flex h-14 items-center border-b px-4">
          <Link to="/" aria-label="PBPS MIS home">
            <Wordmark collapsed={collapsed} />
          </Link>
        </div>
        {!collapsed && (
          <div className="mx-3 mt-3">
            <ProjectSwitcher pid={pid} providerName={providerName} />
          </div>
        )}
        <NavLinks groups={groups} pid={pid} collapsed={collapsed} />
        <div className="border-t p-3">
          <button
            type="button"
            onClick={() => setCollapsed((c) => !c)}
            className={cn(
              "flex w-full items-center gap-2.5 rounded-md px-2 py-1.5 text-[13px] text-muted-foreground hover:bg-sidebar-accent",
              collapsed && "justify-center",
            )}
            aria-label={collapsed ? "Expand sidebar" : "Collapse sidebar"}
          >
            {collapsed ? (
              <ChevronsRight className="h-4 w-4" />
            ) : (
              <>
                <ChevronsLeft className="h-4 w-4" /> Collapse
              </>
            )}
          </button>
        </div>
      </aside>
      <Sheet open={mobile} onOpenChange={setMobile}>
        <SheetContent side="left" className="flex w-64 flex-col bg-sidebar p-0">
          <SheetTitle className="sr-only">Navigation</SheetTitle>
          <div className="flex h-14 items-center border-b px-4">
            <Wordmark />
          </div>
          <NavLinks
            groups={groups}
            pid={pid}
            collapsed={false}
            onNavigate={() => setMobile(false)}
          />
        </SheetContent>
      </Sheet>
      <div className="flex min-w-0 flex-1 flex-col">
        <OfflineBanner />
        <header className="sticky top-0 z-30 flex h-14 items-center gap-3 border-b bg-background/95 px-4 backdrop-blur">
          <Button
            variant="ghost"
            size="icon"
            className="lg:hidden"
            onClick={() => setMobile(true)}
            aria-label="Open navigation"
          >
            <Menu className="h-5 w-5" />
          </Button>
          <div className="min-w-0 flex-1">
            <GlobalSearch pid={pid} />
          </div>
          {canTp && access.providerId && (
            <WhatsDueButton pid={pid} providerId={access.providerId} />
          )}
          <NotificationBell pid={pid} />
          <UserMenu pid={pid} />
        </header>
        <main className="mx-auto w-full max-w-[1440px] flex-1 px-4 py-6 sm:px-6 lg:px-8">
          {children}
        </main>
        <DeveloperFooter className="px-4 pb-5 sm:px-6 lg:px-8" />
      </div>
    </div>
  );
}
