"use client";

import {
  Fragment,
  useEffect,
  useRef,
  type FocusEvent,
  type KeyboardEvent,
  type ReactNode,
} from "react";
import { useCurrentUser } from "@enode/core/current-user/hooks";
import { useTranslation } from "@enode/core/translations/hooks";
import { useAppVersion } from "@enode/core/use-app-version";
import {
  AccountMenuFootnote,
  AccountMenuIdentity,
  AccountMenuItem,
  AccountMenuSeparator,
  moveAccountMenuFocus,
} from "@enode/ui/account/account-menu-parts";
import { useLogoutConfirm } from "@enode/ui/settings/logout-button";

/** Ids of the account menu's entries, in display order. */
export type AccountMenuItemId =
  | "account"
  | "devices"
  | "settings"
  | "help"
  | "signout";

/**
 * One account menu entry: a portal route to open (`href`), the Settings page
 * (`settings`) or the sign-out confirm (`signout`, destructive, own group).
 */
export type AccountMenuItem =
  | { id: "account" | "devices" | "help"; kind: "link"; href: string }
  | { id: "settings"; kind: "settings" }
  | { id: "signout"; kind: "signout" };

/**
 * The account menu's entries in order. Deliberately short: Profile, Plan and
 * Data & import are tabs on the Account page, notifications live on the
 * bell, and there is no ownership transfer. Devices (Recording and Sensors)
 * has its own entry since 17.11.26 (owner request), no longer an Account tab.
 */
export const ACCOUNT_MENU_ITEMS: readonly AccountMenuItem[] = [
  { id: "account", kind: "link", href: "/dashboard/account/profile" },
  { id: "devices", kind: "link", href: "/dashboard/devices" },
  { id: "settings", kind: "settings" },
  { id: "help", kind: "link", href: "/dashboard/help" },
  { id: "signout", kind: "signout" },
];

/**
 * The account menu's sign-out: the same flow as the settings' LogoutButton
 * (`useLogoutConfirm`), so data not uploaded yet is asked about first (ADR 0002
 * amendment 2). `requestSignOut()` starts it; render `signOutDialog` somewhere
 * that stays mounted (also after the menu closes).
 */
export function useBrowserSignOut(): {
  requestSignOut: () => void;
  signOutDialog: ReactNode;
} {
  const { request, dialogs } = useLogoutConfirm();
  return { requestSignOut: request, signOutDialog: dialogs };
}

/** The translated label of a link entry (also the global search's page name). */
export function accountMenuLinkLabel(
  id: "account" | "devices" | "help",
  t: (text: string) => string,
): string {
  switch (id) {
    case "account":
      return t("Account");
    case "devices":
      return t("Devices");
    case "help":
      return t("Help");
  }
}

/** Props of {@link AccountMenu}. */
export type AccountMenuProps = {
  /** Whether the menu is showing. */
  open: boolean;
  /** Closes the menu (Escape, backdrop, after an action). */
  onClose: () => void;
  /** Routes to an account room; the host calls `router.push(href)`. */
  onNavigate: (href: string) => void;
  /** Opens the Settings page. */
  onOpenSettings: () => void;
};

/**
 * The account menu: a compact identity line, then Account, Devices, Settings, Help and
 * (in its own group) Sign out, and the version. Built from the shared
 * `account-menu-parts`, like the tracking app's iPad Account menu.
 * A popover above the sidebar footer from 640px, a bottom sheet below.
 * Focus return after closing is the host's job.
 */
export function AccountMenu({
  open,
  onClose,
  onNavigate,
  onOpenSettings,
}: AccountMenuProps) {
  const { t } = useTranslation();
  const user = useCurrentUser();
  const { requestSignOut, signOutDialog } = useBrowserSignOut();
  const version = useAppVersion();
  const menuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    menuRef.current?.querySelector<HTMLElement>('[role="menuitem"]')?.focus();
  }, [open]);

  // Escape anywhere closes the menu (the menu's own onKeyDown only sees
  // keys while focus is inside it).
  useEffect(() => {
    if (!open) return;
    const onDocKeyDown = (e: globalThis.KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    document.addEventListener("keydown", onDocKeyDown);
    return () => document.removeEventListener("keydown", onDocKeyDown);
  }, [open, onClose]);

  const go = (href: string) => {
    onClose();
    onNavigate(href);
  };

  // Close when focus leaves the menu, except into the sign-out dialog.
  function onFocusOut(e: FocusEvent<HTMLDivElement>) {
    const next = e.relatedTarget as Node | null;
    if (!next) return;
    if (menuRef.current?.contains(next)) return;
    if (next instanceof Element && next.closest('[role="dialog"], [role="alertdialog"]')) return;
    onClose();
  }

  function onKeyDown(e: KeyboardEvent<HTMLDivElement>) {
    if (e.key === "Escape") {
      e.stopPropagation();
      onClose();
      return;
    }
    moveAccountMenuFocus(e, menuRef.current);
  }

  return (
    <>
      {open && (
        <>
          <div
            aria-hidden="true"
            className="fixed inset-0 z-55"
            onClick={onClose}
          />
          <div
            ref={menuRef}
            role="menu"
            aria-label={t("Account")}
            onKeyDown={onKeyDown}
            onBlur={onFocusOut}
            className="fixed inset-x-0 bottom-0 z-60 max-h-[85vh] overflow-y-auto rounded-t-2xl border border-surface-stroke bg-surface-base p-2 pb-[calc(8px+env(safe-area-inset-bottom))] shadow-prominent sm:inset-x-auto sm:bottom-[84px] sm:left-6 sm:max-h-none sm:w-[300px] sm:rounded-2xl sm:pb-2"
          >
            <AccountMenuIdentity
              user={
                user
                  ? { id: user.id, name: user.name ?? "", email: user.email ?? null }
                  : null
              }
            />
            <AccountMenuSeparator />
            {ACCOUNT_MENU_ITEMS.map((item) => {
              switch (item.kind) {
                case "link":
                  return (
                    <AccountMenuItem
                      key={item.id}
                      label={accountMenuLinkLabel(item.id, t)}
                      onSelect={() => go(item.href)}
                    />
                  );
                case "settings":
                  return (
                    <AccountMenuItem
                      key={item.id}
                      label={t("Settings")}
                      onSelect={() => {
                        onClose();
                        onOpenSettings();
                      }}
                    />
                  );
                default:
                  return (
                    <Fragment key={item.id}>
                      <AccountMenuSeparator />
                      <AccountMenuItem
                        label={t("Sign out")}
                        ariaLabel={t("Sign out of this device")}
                        destructive
                        onSelect={() => {
                          onClose();
                          requestSignOut();
                        }}
                      />
                    </Fragment>
                  );
              }
            })}
            {version && (
              <AccountMenuFootnote>
                {t("Version {version}", { version })}
              </AccountMenuFootnote>
            )}
          </div>
        </>
      )}
      {signOutDialog}
    </>
  );
}
