"use client";

import {
  useHasPrivilege,
  usePrivilegeAccess,
} from "@enode/core/auth/use-privilege";
import { isAthleteRole, isOwnerRole } from "@enode/core/auth/role";
import { useCurrentUser } from "@enode/core/current-user/hooks";
import type { TranslateFn } from "@enode/core/translations/hooks";
import {
  CalendarIcon,
  ChartBarFillIcon as InsightsIcon,
  ClipboardFillIcon as WorkoutsIcon,
  ClockFillIcon as HistoryIcon,
  DumbbellFillIcon as ExercisesIcon,
  Person2FillIcon as UsersIcon,
  PersonTextRectangleFillIcon as PerformanceIcon,
  GlobeIcon as QuestionnaireServiceIcon,
  Rectangle3GroupFillIcon as DashboardIcon,
  TagFillIcon as TagIcon,
  TrophyFillIcon as LiveHubIcon,
  WrenchFillIcon as WrenchIcon,
} from "@enode/ui/icons";
import { TOUR_TARGET } from "../tours/tour-targets";
import { useShowDevUi } from "./dev-ui";
import { showDeveloperNav } from "./sidebar-developer";
import { navLockState, type NavLockState } from "./sidebar-nav-lock";

// The sidebar's destinations and who sees which. One source for the sidebar
// itself and the global search (docs/global-search.md), so the search can never
// offer a page the sidebar hides, or miss one it shows.

export type IconComponent = (props: { className?: string }) => React.JSX.Element;

export type NavItem = {
  labelKey: string;
  href: string;
  icon: IconComponent;
  exact?: boolean;
  // Marks the rendered link as a spotlight-tour anchor (`data-tour`) — see
  // src/tours/tour-targets.ts.
  tourId?: string;
};

// Grouped nav. Every section carries a muted heading above its items.
// `labelKey`/`headingKey` are the literal English source strings the i18n
// catalog keys off — wrapped in t() at render time (see `navLabel`).
export type NavSection = { headingKey?: string; tourId?: string; items: NavItem[] };

const NAV: NavSection[] = [
  {
    headingKey: "Workspace",
    items: [
      {
        labelKey: "Dashboard",
        href: "/dashboard",
        icon: DashboardIcon,
        exact: true,
      },
      {
        labelKey: "Live Hub",
        href: "/dashboard/live",
        icon: LiveHubIcon,
      },
      {
        labelKey: "Planner",
        href: "/dashboard/planner",
        icon: CalendarIcon,
        tourId: TOUR_TARGET.sidebarPlanner,
      },
    ],
  },
  {
    headingKey: "Manage",
    items: [
      {
        labelKey: "Users",
        href: "/dashboard/users",
        icon: UsersIcon,
        tourId: TOUR_TARGET.sidebarUsers,
      },
      {
        labelKey: "Exercises",
        href: "/dashboard/exercises",
        icon: ExercisesIcon,
      },
      { labelKey: "Workouts", href: "/dashboard/workouts", icon: WorkoutsIcon },
      { labelKey: "Tags", href: "/dashboard/tags", icon: TagIcon },
    ],
  },
  {
    headingKey: "Analyze",
    tourId: TOUR_TARGET.sidebarAnalyze,
    items: [
      {
        labelKey: "Insights",
        href: "/dashboard/data/insights",
        icon: InsightsIcon,
      },
      {
        labelKey: "Profiles",
        href: "/dashboard/data/performance",
        icon: PerformanceIcon,
      },
      {
        labelKey: "History",
        href: "/dashboard/data/history",
        icon: HistoryIcon,
      },
    ],
  },
  {
    headingKey: "Developer",
    items: [
      // Both entries are dev-only, spread out of a production build entirely
      // and additionally filtered by `showDevUi` (see the nav filter below), so
      // the whole Developer heading disappears with them.
      ...(process.env.NODE_ENV !== "production"
        ? [
            // The questionnaire service's console. The service itself is served
            // from the unlinked /questionnaire route and consumed by the mobile
            // app; this page is where you preview it and read what it emits.
            {
              labelKey: "Questionnaire service",
              href: "/dashboard/questionnaire-service",
              icon: QuestionnaireServiceIcon,
            },
            // Dev-only sandbox for shared components.
            { labelKey: "Debug", href: "/dashboard/debug", icon: WrenchIcon },
          ]
        : []),
    ],
  },
];

/** What {@link useSidebarNav} returns. */
export type SidebarNav = {
  /** The sections the signed-in user sees, empty sections left out. */
  sections: NavSection[];
  /** Insights: shown, shown with a lock (the plan is the reason) or hidden. */
  insightsState: NavLockState;
  /** The profile's first read is still on its way: gated entries are unknown. */
  loading: boolean;
  /**
   * The sections the sidebar lays out. While `loading` this is the optimistic
   * full list (render {@link isGatedNavItem} entries as placeholders);
   * otherwise equal to `sections`.
   */
  layoutSections: NavSection[];
};

/** Entries whose visibility depends on the profile (privileges / role). */
export function isGatedNavItem(href: string): boolean {
  return (
    href === "/dashboard/debug" ||
    href === "/dashboard/questionnaire-service" ||
    href === "/dashboard/users" ||
    href === "/dashboard/data/insights" ||
    href === "/dashboard/live"
  );
}

function filterNav(show: {
  showDebugTools: boolean;
  showUsers: boolean;
  showInsights: boolean;
  showLiveHub: boolean;
}): NavSection[] {
  return NAV.map((section) => ({
    ...section,
    items: section.items.filter((item) => {
      // Debug and the questionnaire service are developer tools for previewing
      // the service, not product surfaces. Their routes stay reachable by URL.
      if (
        item.href === "/dashboard/debug" ||
        item.href === "/dashboard/questionnaire-service"
      )
        return show.showDebugTools;
      if (item.href === "/dashboard/users") return show.showUsers;
      if (item.href === "/dashboard/data/insights") return show.showInsights;
      if (item.href === "/dashboard/live") return show.showLiveHub;
      return true;
    }),
  })).filter((section) => section.items.length > 0);
}

/**
 * The sidebar destinations the signed-in user may see. Hides the dev-only
 * pages outside the dev-UI preview, Users without a write-tier privilege, Live
 * Hub on the server's "no", and Insights for an athlete.
 */
export function useSidebarNav(): SidebarNav {
  const user = useCurrentUser();
  // The Users page manages users; without any write-tier privilege there's
  // nothing to do there, so its nav entry is hidden (the route itself also
  // guards — see users/page.tsx). Call all three hooks unconditionally, then
  // combine — no short-circuiting.
  const canWriteAthlete = useHasPrivilege("writeUserAthlete");
  const canWriteCoach = useHasPrivilege("writeUserTrainer");
  const canWriteAdmin = useHasPrivilege("writeUserAdmin");
  const canWriteAnyUser = canWriteAthlete || canWriteCoach || canWriteAdmin;
  // Insights is the custom-charts surface. Without writeCustomCharts it stays
  // in the nav with a lock when the plan is the reason (the route shows the
  // paywall in place); an athlete does not see it (see data/insights/page.tsx).
  const insightsState = navLockState({
    access: usePrivilegeAccess("writeCustomCharts"),
    isAthlete: isAthleteRole(user?.role),
  });
  // Live Hub is privilege-gated the same way (route guard in live/page.tsx).
  // Its entry stays while the profile cannot be read: that is not a "no", and
  // the page shows what it can without the server. Only the server's "no"
  // (and the first read, to spare a flash) hides it.
  const liveHubAccess = usePrivilegeAccess("showLiveHubSection");
  const canShowLiveHub =
    liveHubAccess === "granted" || liveHubAccess === "unknown";
  // Drop the dev-only "Debug" entry while previewing the production UI (in a
  // prod build it's already absent). The Debug page stays reachable at
  // /dashboard/debug to switch the preview back off.
  const isDevBuild = useShowDevUi();
  const showDevUi = showDeveloperNav({
    isDevBuild,
    isOwner: isOwnerRole(user?.role),
  });
  const sections = filterNav({
    showDebugTools: showDevUi,
    showUsers: canWriteAnyUser,
    showInsights: insightsState !== "hidden",
    showLiveHub: canShowLiveHub,
  });
  // While the profile's first read is on its way the gated entries are not
  // known. The sidebar reserves their rows (as placeholders) so the list does
  // not shift when the answer arrives; the global search keeps `sections`.
  const loading = liveHubAccess === "loading";
  const layoutSections = loading
    ? filterNav({
        showDebugTools: isDevBuild,
        showUsers: true,
        showInsights: true,
        showLiveHub: true,
      })
    : sections;
  return { sections, layoutSections, loading, insightsState };
}

/**
 * The translated label of a nav item. Mapped to explicit literal t(...) calls
 * so the i18n extractor picks them up — a dynamic t(variable) is silently
 * skipped.
 */
export function navLabel(t: TranslateFn, key: string): string {
  switch (key) {
    case "Dashboard":
      return t("Dashboard");
    case "Live Hub":
      return t("Live Hub");
    case "Planner":
      return t("Planner");
    case "Users":
      return t("Users");
    case "Exercises":
      return t("Exercises");
    case "Workouts":
      return t("Workouts");
    case "Tags":
      return t("Tags");
    case "History":
      return t("History");
    case "Profiles":
      return t("Profiles");
    case "Insights":
      return t("Insights");
    case "Questionnaire service":
      return t("Questionnaire service");
    default:
      return key;
  }
}

/** The translated heading of a nav section (literal t(...) calls, as above). */
export function navSectionHeading(t: TranslateFn, key: string): string {
  switch (key) {
    case "Workspace":
      return t("Workspace");
    case "Manage":
      return t("Manage");
    case "Analyze":
      return t("Analyze");
    case "Developer":
      return t("Developer");
    default:
      return key;
  }
}
