"use client";

import { HEADER_ICON_BUTTON } from "@enode/ui/header-button";
import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { usePrivilegeAccess } from "@enode/core/auth/use-privilege";
import { isAthleteRole } from "@enode/core/auth/role";
import { useCurrentUser } from "@enode/core/current-user/hooks";
import { useTextContent } from "@enode/core/text-content/useTextContent";
import { refreshCurrentUser } from "@enode/core/current-user/store";
import { useTranslation } from "@enode/core/translations/hooks";
import {
  LockFillIcon,
  MagnifyingGlassIcon,
  SidebarIcon,
  SquareAndArrowUpIcon,
} from "@enode/ui/icons";
import { AthleteAvatar } from "@enode/ui/athlete-avatar";
import { Skeleton } from "@enode/ui/feedback/skeleton";
import { HEADER_MIN_HEIGHT } from "@enode/ui/header-height";
import { sidebarRoleWord } from "./sidebar-account";
import { navLockState } from "./sidebar-nav-lock";
import {
  isGatedNavItem,
  navLabel,
  navSectionHeading,
  useSidebarNav,
} from "./sidebar-nav";
import { useGlobalSearchShortcutLabel } from "./global-search/global-search-hotkey";
import { EnodeWordmark } from "./enode-wordmark";
import { SidebarNoticeStack } from "./notices/sidebar-notice-stack";
import { useActionDrawer } from "./action-drawer";
import { NotificationBell } from "./notifications/notification-bell";
import { usePaywalls } from "./paywall/paywall-content";
import { PaywallPopup } from "./paywall/paywall-popup";

// On-demand action drawers, triggered from the footer tools menu rather than a
// nav destination (the flow is a one-off task, not a browsable page — the hosts
// live in AppShell).
export type DrawerAction = "migration" | "export";

// Brand accent (not body text): `text-brand-red-orange` is the real brand
// colour, not the darker `.text-foreground-red-orange` used for text/links.
// Active-item treatment, ported from the old portal: the item lifts into a
// bordered, surface-on-surface chip with the red-orange accent. In dark mode
// `--background` is pure black — a black chip on the card reads like a hole —
// so the active fill uses the hover gray (surface-base-muted) there instead.
const ACTIVE =
  "border-surface-stroke bg-background dark:bg-surface-base-muted text-brand-red-orange shadow-sm";
const INACTIVE =
  "border-transparent text-foreground-muted hover:bg-surface-base-muted hover:text-foreground-default";

// Footer icon buttons — uniform 40px round targets. The icon buttons carry a
// border so the small glyphs read as evenly-sized circles next to the avatar
// (which is a filled 40px circle and needs no border).
const FOOTER_BUTTON_CLASS =
  "flex size-10 shrink-0 items-center justify-center rounded-full border border-surface-stroke text-foreground-muted transition-colors hover:bg-surface-base-muted hover:text-foreground-default";
// The account button: avatar + name and role, taking the width the export
// and bell buttons leave (the 240px column leaves the text about 64px with
// both buttons, about 112px with the bell alone); both lines truncate.
const FOOTER_ACCOUNT_BUTTON_CLASS =
  "flex min-h-11 min-w-0 flex-1 items-center gap-2 rounded-full pr-1.5 text-left transition-colors hover:bg-surface-base-muted";

// The sidebar body — flush chrome with no card of its own: on desktop it sits
// on the shell's window colour beside the content card, on phones inside the
// overlay drawer's panel (see app-shell.tsx). Shared by the persistent desktop
// column and the mobile drawer; `onNavigate` lets the mobile drawer close on
// tap.
export function Sidebar({
  onNavigate,
  onOpenAccountMenu,
  accountMenuOpen,
  onOpenDrawer,
  onClose,
  onOpenNotifications,
  onOpenSearch,
}: {
  onNavigate?: () => void;
  // Opens the account menu (the footer avatar); the menu itself lives in AppShell.
  onOpenAccountMenu?: () => void;
  // Whether the account menu is open; focus returns to the avatar on close.
  accountMenuOpen?: boolean;
  // Opens one of the on-demand action drawers (data export / migration).
  onOpenDrawer?: (action: DrawerAction) => void;
  // Collapses the sidebar (the in-card control, mirroring the tracking app).
  onClose?: () => void;
  // Overlay mode: the bell asks the shell to close this sidebar and present
  // the notifications sheet (one overlay at a time).
  onOpenNotifications?: () => void;
  // Opens the global search (docs/global-search.md); the dialog lives in AppShell.
  onOpenSearch?: () => void;
}) {
  const { t } = useTranslation();
  const pathname = usePathname();
  // The signed-in user for the footer row (avatar + name). Not preloaded at
  // app start, so kick off the fetch here; the profile drawer reads the same
  // store, so edits there reflect in the footer.
  const user = useCurrentUser();
  useEffect(() => {
    void refreshCurrentUser();
  }, []);
  const { openExportDrawer } = useActionDrawer();
  // Export as a share-style footer action for coaches and owners (the team
  // export drawer); athletes export their own data from Account › Data & import.
  // The plan decides like on Users / Exercises / Sessions (featureDataExport):
  // without it the button stays with a lock and opens the offer (the Insights
  // pattern, see sidebar-nav-lock.ts).
  const exportState = navLockState({
    access: usePrivilegeAccess("featureDataExport"),
    isAthlete: user ? isAthleteRole(user.role) : undefined,
  });
  const [exportPaywallOpen, setExportPaywallOpen] = useState(false);
  const paywalls = usePaywalls();

  // The destinations this user sees — shared with the global search.
  const { layoutSections: nav, loading: navLoading, insightsState } =
    useSidebarNav();
  const shortcutLabel = useGlobalSearchShortcutLabel();
  const avatarRef = useRef<HTMLButtonElement>(null);
  const wasMenuOpen = useRef(false);
  useEffect(() => {
    if (wasMenuOpen.current && !accountMenuOpen) avatarRef.current?.focus();
    wasMenuOpen.current = !!accountMenuOpen;
  }, [accountMenuOpen]);
  // The server's own name of a role the portal has no word for (e.g.
  // Administrator), so such a person is not labelled "Coach".
  const serverRoleName = useTextContent(user?.role?.nameTextContentID)?.trim();
  const roleWord = sidebarRoleWord(t, user?.role, serverRoleName);
  // After roleWord: the label reads it.
  const avatarLabel = accountAvatarLabel();

  function accountAvatarLabel(): string {
    if (!user) return t("Account");
    const name = user.name ?? "";
    const organisation = user.organisation?.name?.trim();
    const role = roleWord;
    if (!role) {
      return organisation
        ? t("{name} · {organisation}", { name, organisation })
        : name;
    }
    return organisation
      ? t("{name} · {role} at {organisation}", { name, role, organisation })
      : t("{name} · {role}", { name, role });
  }

  return (
    <div className="flex h-full w-full flex-col">
      {/* Header: the wordmark (home link) + the collapse control — same chrome
          as the tracking sidebar's header (station-management-content.tsx). */}
      <div
        className={`${HEADER_MIN_HEIGHT} flex shrink-0 items-center justify-between gap-2 px-4 py-4`}
      >
        <Link
          href="/dashboard"
          onClick={onNavigate}
          aria-label={t("enode — go to dashboard")}
          className="inline-flex rounded-lg transition-opacity hover:opacity-80"
        >
          <EnodeWordmark className="h-7 w-auto text-foreground-default" />
        </Link>
        {onClose && (
          <button
            type="button"
            onClick={onClose}
            aria-label={t("Collapse sidebar")}
            className={HEADER_ICON_BUTTON}
          >
            <SidebarIcon className="size-5" />
          </button>
        )}
      </div>

      {/* Global search: a field-shaped button that opens the search dialog
          (also ⌘K / Ctrl+K from anywhere in the portal). */}
      {onOpenSearch && (
        <div className="shrink-0 px-4 pb-1">
          <button
            type="button"
            onClick={onOpenSearch}
            aria-haspopup="dialog"
            aria-keyshortcuts="Meta+K Control+K"
            className="group flex h-11 w-full items-center gap-2.5 rounded-xl border border-surface-stroke bg-background px-3 text-left text-foreground-muted shadow-sm outline-none transition-colors hover:border-foreground-more-muted hover:text-foreground-default focus-visible:border-foreground-red-orange focus-visible:ring-2 focus-visible:ring-foreground-red-orange/25 lg:h-9"
          >
            <MagnifyingGlassIcon className="size-4 shrink-0 transition-colors group-hover:text-brand-red-orange" />
            <span className="body-small flex-1 truncate">{t("Search")}</span>
            <kbd className="inline-flex h-5 shrink-0 items-center rounded-md border border-surface-stroke bg-surface-base px-1.5 font-sans stat-small text-foreground-more-muted shadow-[inset_0_-1px_0_var(--surface-stroke)]">
              {shortcutLabel}
            </kbd>
          </button>
        </div>
      )}

      {/* Nav */}
      <nav className="scrollbar-none flex-1 overflow-y-auto px-4 py-2">
        {nav.map((section, index) => (
          <div
            key={section.headingKey ?? "primary"}
            data-tour={section.tourId}
            className={index > 0 ? "mt-4" : ""}
          >
            {section.headingKey ? (
              <div className="heading-small px-2 pt-1 pb-1 tracking-wide text-foreground-more-muted uppercase">
                {navSectionHeading(t, section.headingKey)}
              </div>
            ) : null}
            <div className="grid items-start gap-0.5">
              {section.items.map((item) => {
                const active = item.exact
                  ? pathname === item.href
                  : pathname.startsWith(item.href);
                const Icon = item.icon;
                if (navLoading && isGatedNavItem(item.href)) {
                  // Reserves the row until the privileges are known.
                  return (
                    <div
                      key={item.href}
                      aria-hidden
                      className="flex h-11 items-center gap-2 pl-2 lg:h-8"
                    >
                      <Skeleton className="size-4.5 shrink-0" />
                      <Skeleton className="h-3.5 w-24" />
                    </div>
                  );
                }
                return (
                  <Link
                    key={item.href}
                    href={item.href}
                    onClick={onNavigate}
                    data-tour={item.tourId}
                    aria-current={active ? "page" : undefined}
                    className={`flex h-11 min-w-0 items-center gap-2 whitespace-nowrap rounded-lg border pl-2 lg:h-8 transition-[background-color,border-color,box-shadow] ${
                      active ? ACTIVE : INACTIVE
                    }`}
                  >
                    <Icon className="size-4.5 shrink-0" />
                    <span className="heading-section truncate">
                      {navLabel(t, item.labelKey)}
                    </span>
                    {item.href === "/dashboard/data/insights" &&
                    insightsState === "locked" ? (
                      <>
                        <LockFillIcon
                          aria-hidden
                          className="size-3.5 shrink-0 text-foreground-more-muted"
                        />
                        <span className="sr-only">{t("Not in your plan")}</span>
                      </>
                    ) : null}
                  </Link>
                );
              })}
            </div>
          </div>
        ))}
      </nav>

      {/* Rail notices — the connection note (only while unreachable) + the
          migration launch card, pinned just above the footer. One open at a
          time, the announcement dismissible and persisted. "Start migration"
          opens the migration drawer; on the mobile overlay we also close the
          sidebar so the drawer isn't hidden behind it. */}
      <SidebarNoticeStack
        onStartMigration={() => {
          onOpenDrawer?.("migration");
          onNavigate?.();
        }}
        onNavigate={onNavigate}
      />

      {/* Footer — the account button (avatar, name and role; opens the
          account menu), the export share button (coaches and owners: the team
          export drawer) and the bell. */}
      <div className="mt-auto shrink-0 px-3 py-2">
        <div className="flex items-center gap-2">
          <button
            ref={avatarRef}
            type="button"
            onClick={onOpenAccountMenu}
            aria-label={
              user
                ? t("Account menu: {name}", { name: avatarLabel })
                : t("Account menu")
            }
            title={avatarLabel}
            aria-haspopup="menu"
            aria-expanded={!!accountMenuOpen}
            className={FOOTER_ACCOUNT_BUTTON_CLASS}
          >
            {user ? (
              <AthleteAvatar
                userID={user.id ?? ""}
                name={user.name ?? ""}
                size={40}
                className="body-small font-medium"
              />
            ) : (
              <Skeleton rounded="full" className="size-10 shrink-0" />
            )}
            {user ? (
              <span className="flex min-w-0 flex-1 flex-col">
                <span className="body-small truncate font-medium text-foreground-default">
                  {user.name ?? ""}
                </span>
                {roleWord ? (
                  <span className="body-small truncate text-foreground-muted">
                    {roleWord}
                  </span>
                ) : null}
              </span>
            ) : (
              <span aria-hidden className="flex min-w-0 flex-1 flex-col gap-1.5">
                <Skeleton className="h-3 w-24" />
                <Skeleton className="h-3 w-14" />
              </span>
            )}
          </button>
          <div className="flex shrink-0 items-center gap-2">
            {navLoading && exportState === "hidden" && (
              <Skeleton rounded="full" className="size-10 shrink-0" />
            )}
            {exportState === "visible" && (
              <button
                type="button"
                onClick={() => {
                  onNavigate?.();
                  openExportDrawer();
                }}
                aria-label={t("Export data")}
                title={t("Export data")}
                className={FOOTER_BUTTON_CLASS}
              >
                <SquareAndArrowUpIcon className="size-5" />
              </button>
            )}
            {exportState === "locked" && (
              <button
                type="button"
                onClick={() => setExportPaywallOpen(true)}
                aria-label={t("Export data — not in your plan")}
                title={t("Export data — not in your plan")}
                className={`${FOOTER_BUTTON_CLASS} relative`}
              >
                <SquareAndArrowUpIcon className="size-5" />
                <LockFillIcon
                  aria-hidden
                  className="absolute -right-0.5 -bottom-0.5 size-3.5 rounded-full bg-surface-base text-foreground-more-muted"
                />
              </button>
            )}
            {/* `onNavigate` closes the mobile sidebar overlay when the panel
                navigates, so the destination page isn't hidden behind it. */}
            <NotificationBell
              className={FOOTER_BUTTON_CLASS}
              onNavigate={onNavigate}
              onOpenSheet={onOpenNotifications}
            />
          </div>
        </div>
      </div>
      <PaywallPopup
        content={paywalls.dataExport}
        open={exportPaywallOpen}
        onClose={() => setExportPaywallOpen(false)}
      />
    </div>
  );
}
