"use client";

import { useEffect, useState, type ReactNode } from "react";
import { useAnnouncementAnchor } from "@enode/core/announcements/hooks";
import { loadCurrentUser } from "@enode/core/current-user/store";
import { useTranslation } from "@enode/core/translations/hooks";
import { useUserSettingSaves } from "@enode/core/user-app-settings/instant-save";
import { useStoreState } from "@enode/core/store-kit/hooks";
import { useUserAppSettings } from "@enode/core/user-app-settings/hooks";
import {
  loadUserAppSettings,
  userAppSettingsStatus,
} from "@enode/core/user-app-settings/store";
import { RequireData } from "@enode/ui/feedback/require-data";
import { DrawerStack } from "@enode/ui/drawer-stack";
import { UnderlineTabs } from "@enode/ui/underline-tabs";
import {
  useNotificationChoices,
  type NotificationChoices,
} from "./notifications-view";
import { DeveloperGroup } from "./pages/developer-group";
import {
  GroupedDrawerView,
  ScreenColumnClassContext,
} from "./pages/grouped-drawer-view";
import { LanguageUnitsPage } from "./pages/language-units-page";
import { LegalPage } from "./pages/legal-page";
import { LiveDisplayPage } from "./pages/live-display-page";
import {
  NotificationsRemindersPage,
  notificationsDeviceSection,
  notificationsSectionEmpty,
} from "./pages/notifications-reminders-page";
import { SettingsTabBody } from "./pages/settings-home";
import {
  SettingsHostContext,
  useSettingsHost,
  type SettingsHostValue,
} from "./pages/settings-host-context";
import { TipsPage } from "./pages/tips-page";
import { TrainingPage } from "./pages/training-page";
import {
  settingsTabLabel,
  type SettingsPageId,
  type SettingsPlatform,
  type SettingsSectionId,
} from "./pages/types";
import { useSaveFeedback } from "./save-feedback";
import { SettingsLookProvider } from "./settings-look";
import {
  initialSettingsTab,
  settingsTabIds,
  type SettingsFocusSection,
} from "./settings-sections";

/** Host-provided content for the device-only parts of Settings (tracking app). */
export type SettingsDevicePages = {
  /** The text-size, rest-timer, sound and during-a-set groups of This device. */
  displaySound?: ReactNode;
  /** The "Only on this device" rows of Notifications & reminders (reminder + push permission). */
  notificationsDevice?: ReactNode;
  /** The device-name field of This device. */
  thisDeviceName?: ReactNode;
  /** The "Training stations − n +" row of This device (tracking). */
  thisDeviceStations?: ReactNode;
  /** The schedule status line ("Schedule up to date", "Sync now") of This device. */
  thisDeviceSchedule?: ReactNode;
  /** The on-device videos block of This device. */
  deviceVideos?: ReactNode;
  /**
   * Extra rows of Settings › Legal, after Terms and Privacy (17.11.26:
   * "Manual & safety", the sensor manual with its safety notes and approvals;
   * the portal passes its own row through its Settings host).
   */
  legal?: ReactNode;
  /**
   * The account's sensors (tracking: "My sensors" and the sensor manual). Not
   * device-only: it closes the Training tab, under "On all your devices".
   *
   * @deprecated 17.11.26: the sensors moved to Account › Devices › Sensors
   * (owner request: sensors belong to Devices, not to the training
   * settings). The tracking app no longer fills it; still rendered when a
   * host passes it.
   */
  sensors?: ReactNode;
};

/** The host content of {@link SettingsScreen}. */
export type SettingsContentProps = {
  /** Which host renders Settings; decides the rows. Default `"portal"`. */
  platform?: SettingsPlatform;
  /**
   * App-only: a per-device distance threshold set from the training menu,
   * which wins over the account-level value. Training shows it with a Reset.
   * Omit or pass `null` when there is none (and in the portal).
   */
  distanceOverride?: { cm: number; onReset: () => void } | null;
  /** Host content for the device-only parts, see {@link SettingsDevicePages}. */
  devicePages?: SettingsDevicePages;
  /** Opens the host's debug screen; adds a "Debug" row to the Developer group. */
  onOpenDebug?: () => void;
};

/** Props of {@link SettingsScreen}. */
export type SettingsScreenProps = SettingsContentProps & {
  /** Whether Settings is shown. */
  open: boolean;
  /** Called when the user leaves Settings (Back on the Settings screen). */
  onClose: () => void;
  /**
   * The tab to open. `"thisDevice"` (or the legacy `"displaySound"`) opens
   * the "This device" tab on tracking; an account-wide section id opens that
   * tab; every other page opens Training.
   */
  initialPage?: SettingsPageId;
  /**
   * Legacy open request: `"storage"` opens "This device" on tracking like
   * `initialPage="thisDevice"`; `"questionnaires"` opens Training.
   */
  focusSection?: SettingsFocusSection | null;
  /**
   * Re-request token: when it changes while open, Settings starts again on
   * the requested tab, e.g. when a Settings link is tapped while Settings is
   * already open.
   */
  requestKey?: number | string;
  /** Overrides the screen column classes (default `mx-auto w-full max-w-2xl px-6`). */
  columnClassName?: string;
};

// Matches the slide-out duration in drawer-stack.tsx.
const CLOSE_MS = 320;

/**
 * Settings as a full screen in the enode look: page background, a round back
 * button + large title with the shared underline tabs pinned under it,
 * content in a centred `max-w-2xl` column. One tab per account-wide section
 * (Training, Live display, Notifications, Language & units, Tips) under an
 * "On all your devices" note, on tracking a first "This device" tab with
 * the device-only settings, and a last "Legal" tab (17.11.26). Notifications is left out when it has nothing to
 * show; the Developer group sits at the bottom of Training. All controls
 * save at once; every user-app-setting save shows a "Saved" toast.
 *
 * The tab is in-memory state: kept while Settings stays open, and on every
 * open (or re-request) it starts on the requested tab, Training by default
 * (see {@link SettingsScreenProps.initialPage}). Every open also re-fetches
 * the user app settings and the current user. It only mounts while open (or
 * in the brief window after closing).
 *
 * Presented as a `DrawerStack` `"screen"`: covers the full viewport by
 * default, or the positioned content area when wrapped in
 * `<ContainmentProvider value="container">` (iPad: next to the rail; portal:
 * next to the sidebar). Back closes it (`onClose`).
 *
 * @remarks Live display needs the `display`, `metrics` and `user-app-settings`
 * stores preloaded (e.g. via the host layout's loaders); without display bases
 * and metrics its Focus metrics list stays empty.
 */
export function SettingsScreen({
  open,
  onClose,
  platform = "portal",
  initialPage,
  focusSection = null,
  requestKey,
  columnClassName,
  distanceOverride = null,
  devicePages,
  onOpenDebug,
}: SettingsScreenProps) {
  const { t } = useTranslation();
  const [mounted, setMounted] = useState(false);
  // Bumped on every open and used as the home view's key, so a reopen within
  // the close animation (while still mounted) starts from a fresh view.
  const [openCount, setOpenCount] = useState(0);
  // The requestKey last applied while open; part of the home view's key, so
  // a re-request remounts the home and re-applies the initial tab.
  // Updated in the same effect flush as openCount on open (one remount, not two).
  const [shownRequestKey, setShownRequestKey] = useState(requestKey);
  // `screen:settings` announcement anchor, in both apps.
  useAnnouncementAnchor("settings", open);
  /* eslint-disable react-hooks/set-state-in-effect */
  useEffect(() => {
    if (open) {
      setMounted(true);
      setOpenCount((n) => n + 1);
      // Re-fetch every open so the sections show the current server state,
      // not a stale cache from app start.
      loadUserAppSettings().catch((err) => {
        console.error("Failed to refresh user app settings:", err);
      });
      loadCurrentUser().catch((err) => {
        console.error("Failed to load current user:", err);
      });
      return;
    }
    const id = window.setTimeout(() => setMounted(false), CLOSE_MS);
    return () => window.clearTimeout(id);
  }, [open]);
  useEffect(() => {
    if (open) setShownRequestKey(requestKey);
  }, [open, requestKey]);
  /* eslint-enable react-hooks/set-state-in-effect */

  if (!mounted) return null;

  const hostValue: SettingsHostValue = {
    platform,
    layout: "tabs",
    distanceOverride,
    devicePages,
  };
  // Look and host content sit outside the DrawerStack so every stack entry
  // gets them.
  const screen = (
    <SettingsLookProvider value="screen">
      <SettingsHostContext.Provider value={hostValue}>
        <DrawerStack
          open={open}
          onClose={onClose}
          ariaLabel={t("Settings")}
          presentation="screen"
          root={
            <SettingsHomeView
              key={`${openCount}:${String(shownRequestKey ?? "")}`}
              platform={platform}
              initialTab={initialSettingsTab({
                initialPage,
                focusSection,
                platform,
              })}
              onOpenDebug={onOpenDebug}
            />
          }
        />
      </SettingsHostContext.Provider>
    </SettingsLookProvider>
  );
  return columnClassName ? (
    <ScreenColumnClassContext.Provider value={columnClassName}>
      {screen}
    </ScreenColumnClassContext.Provider>
  ) : (
    screen
  );
}

// The Settings screen body (the stack's root view): the tab row in the
// header, the active tab's body below. Remounted (see the screen's key) on
// every open and re-request, so it starts on `initialTab` again.
function SettingsHomeView({
  platform,
  initialTab,
  onOpenDebug,
}: {
  platform: SettingsPlatform;
  initialTab: SettingsSectionId;
  onOpenDebug?: () => void;
}) {
  const { t } = useTranslation();
  const sections = useSettingsSections();
  const [picked, setPicked] = useState(initialTab);
  // Notifications is left out when it has nothing to show.
  const tabIds = settingsTabIds({ platform }).filter(
    (id) => !sections.empty(id),
  );
  const tab = tabIds.includes(picked) ? picked : (tabIds[0] ?? "training");

  return (
    <GroupedDrawerView
      title={t("Settings")}
      scrollResetKey={tab}
      subheader={
        <UnderlineTabs
          tabs={tabIds.map((id) => ({ id, label: settingsTabLabel(id, t) }))}
          activeId={tab}
          ariaLabel={t("Settings")}
          onSelect={setPicked}
        />
      }
    >
      <SettingsTabBody
        tab={tab}
        section={sections.section}
        notice={sections.notice}
        developer={<DeveloperGroup onOpenDebug={onOpenDebug} />}
      />
    </GroupedDrawerView>
  );
}

/** Return value of {@link useSettingsSections}. */
export type SettingsSections = {
  /**
   * The body of one account-wide section, or `null`: Training, Language &
   * units and Tips wait until the user app settings are loaded;
   * Notifications & reminders is `null` when it has nothing to show.
   */
  section: (id: SettingsSectionId) => ReactNode;
  /** Whether a section has nothing to show at all (Notifications & reminders without topics or device rows). */
  empty: (id: SettingsSectionId) => boolean;
  /** An inline load error with Try again when the user app settings failed to load; otherwise `null`. */
  notice: ReactNode;
};

/**
 * The account-wide Settings sections for a host that lays them out itself
 * (the tracking app's Settings screen; the portal's Settings page).
 * Loads the notification choices once and shows one "Saved" toast per saved
 * user-app setting while mounted.
 *
 * @remarks Call it inside `SettingsHostContext` (the platform decides the
 * device rows) and a `SettingsLookProvider value="screen"`. It does not
 * re-fetch the user app settings; the host does that when Settings opens.
 */
export function useSettingsSections(): SettingsSections {
  const host = useSettingsHost();
  const feedback = useSaveFeedback();
  const notifications = useNotificationChoices();
  const settingsReady = useUserAppSettings() != null;
  const settingsLoad = useStoreState(userAppSettingsStatus);
  const settingsFailed = !settingsReady && settingsLoad.status === "error";
  const notificationsDevice = notificationsDeviceSection(host);

  // One toast per saved user-app setting, from every section.
  useUserSettingSaves((e) => {
    if (e.type === "saved") feedback.saved();
  });

  return {
    section: (id) =>
      settingsSectionBody(id, {
        settingsReady,
        notifications,
        notificationsDevice,
      }),
    empty: (id) =>
      id === "notifications" &&
      notificationsSectionEmpty(notifications, notificationsDevice),
    notice: settingsFailed && (
      <UserAppSettingsGate>{null}</UserAppSettingsGate>
    ),
  };
}

// Shows an inline error (with Try again) instead of `children` when the
// user-app-settings record is missing and its load failed (e.g. offline
// launch), so sections don't show every switch as Off.
function UserAppSettingsGate({ children }: { children: ReactNode }) {
  const { t } = useTranslation();
  const state = useStoreState(userAppSettingsStatus);
  const settings = useUserAppSettings();
  if (settings != null) return <>{children}</>;
  return (
    <RequireData
      errorVariant="inline"
      onRetry={() => {
        loadUserAppSettings().catch((err) => {
          console.error("Failed to load user app settings:", err);
        });
      }}
      requirements={[{ label: t("your settings"), state, satisfied: false }]}
    >
      {children}
    </RequireData>
  );
}

// The body of one Settings section, or `null` to leave it out: the sections
// that read the user app settings wait until they are loaded (the screen
// shows one load error at the top instead); Notifications & reminders is left
// out when it has neither device rows nor topics.
function settingsSectionBody(
  id: SettingsSectionId,
  input: {
    settingsReady: boolean;
    notifications: NotificationChoices;
    notificationsDevice: ReactNode;
  },
): ReactNode {
  switch (id) {
    case "training":
      return input.settingsReady ? <TrainingPage /> : null;
    case "liveDisplay":
      return <LiveDisplayPage />;
    case "notifications":
      return notificationsSectionEmpty(
        input.notifications,
        input.notificationsDevice,
      ) ? null : (
        <NotificationsRemindersPage choices={input.notifications} />
      );
    case "languageUnits":
      return input.settingsReady ? <LanguageUnitsPage /> : null;
    case "tips":
      return input.settingsReady ? <TipsPage /> : null;
    case "legal":
      return <LegalPage />;
    case "thisDevice":
      return null;
  }
}
