"use client";

import { Suspense, useEffect } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useAnnouncementAnchor } from "@enode/core/announcements/hooks";
import { loadCurrentUser } from "@enode/core/current-user/store";
import { useTranslation } from "@enode/core/translations/hooks";
import { useStoreState } from "@enode/core/store-kit/hooks";
import {
  loadUserAppSettings,
  userAppSettingsStatus,
} from "@enode/core/user-app-settings/store";
import { InlineAlert } from "@enode/ui/feedback/inline-alert";
import { StalenessHint } from "@enode/ui/feedback/staleness-hint";
import { ScopeBand, SettingsInlineContext } from "@enode/ui/settings/settings-card-group";
import { SettingsLookProvider } from "@enode/ui/settings/settings-look";
import { useSettingsSections } from "@enode/ui/settings/settings-screen";
import { SettingsHostContext } from "@enode/ui/settings/pages/settings-host-context";
import { settingsTabLabel } from "@enode/ui/settings/pages/types";
import { PageShell } from "../../../components/page-shell";
import { UnderlineTabs } from "@enode/ui/underline-tabs";
import { LegalManualPage, LegalManualRow } from "./legal-manual";
import {
  DEFAULT_SETTINGS_TAB,
  parseLegalDoc,
  parseSettingsQuery,
  SETTINGS_TAB_IDS,
  settingsTabHref,
} from "./settings-query";

// Legal's extra row (17.11.26, f-5): "Manual & safety", as in the tracking app.
const PORTAL_HOST = {
  platform: "portal",
  layout: "tabs",
  devicePages: { legal: <LegalManualRow /> },
} as const;

function SettingsTabs() {
  const { t } = useTranslation();
  const router = useRouter();
  const params = useSearchParams();
  const { tab: requested, redirectTo } = parseSettingsQuery(params);
  const legalDoc = parseLegalDoc(params);
  const sections = useSettingsSections();
  useAnnouncementAnchor("settings");

  // A failed refresh is reported by the store status (read below), not here.
  const settingsLoad = useStoreState(userAppSettingsStatus);
  const refreshSettings = () => {
    loadUserAppSettings().catch((err) => {
      console.error("Failed to refresh user app settings:", err);
    });
  };

  // Show the server's current values, not a cache from app start.
  useEffect(() => {
    refreshSettings();
    loadCurrentUser().catch((err) => {
      console.error("Failed to load current user:", err);
    });
  }, []);
  useEffect(() => {
    if (redirectTo) router.replace(`${redirectTo}${window.location.hash}`);
  }, [redirectTo, router]);
  if (redirectTo) return null;

  // Notifications is left out when it has nothing to show (no topics).
  const tabIds = SETTINGS_TAB_IDS.filter((id) => !sections.empty(id));
  const active = tabIds.includes(requested) ? requested : DEFAULT_SETTINGS_TAB;
  const tabs = tabIds.map((id) => ({
    id,
    label: settingsTabLabel(id, t),
    href: settingsTabHref(id, params),
  }));

  return (
    <div className="flex w-full flex-col gap-6 pb-6">
      <div className="flex flex-col gap-3">
        <UnderlineTabs
          tabs={tabs}
          activeId={active}
          ariaLabel={t("Settings")}
          linkComponent={Link}
          replace
        />
        {/* Legal holds no settings, so it says nothing about where they apply. */}
        {active !== "legal" && (
          <ScopeBand
            variant="everywhere"
            label={t("On all your devices")}
            caption={t("Follows your account to all your devices and the portal.")}
            className="pt-2"
          />
        )}
      </div>
      {active !== "legal" && sections.notice}
      {/* Refresh failed: cached settings are still usable (a hint); with
          nothing cached it is an error with a retry. */}
      {active !== "legal" && settingsLoad.status === "error" && (
        settingsLoad.hasData ? (
          <div>
            <StalenessHint onRetry={refreshSettings} />
          </div>
        ) : (
          <InlineAlert onRetry={refreshSettings}>
            {t("Couldn't load your settings.")}
          </InlineAlert>
        )
      )}
      {/* The scope is said once above; the sections leave out their own
          "On all your devices" notes. */}
      <SettingsInlineContext.Provider value>
        {active === "legal" && legalDoc === "manual" ? (
          // Legal's sub-page, in the same column as the tabs' content.
          <section data-find="settings-legal-manual">
            <LegalManualPage />
          </section>
        ) : (
          <section key={active} data-find={`settings-tab-${active}`}>
            {sections.section(active)}
          </section>
        )}
      </SettingsInlineContext.Provider>
    </div>
  );
}

/**
 * Settings: one underline tab per account-wide section (Training, Live
 * display, Notifications, Language & units, Tips) and a last Legal tab
 * (17.11.26), each `?page=<id>`; Legal's "Manual & safety" opens as its
 * sub-page, `?page=legal&doc=manual`.
 * Account page ids forward to the Account area (see `settings-query.ts`).
 */
export default function SettingsPage() {
  const { t } = useTranslation();
  return (
    <PageShell width="narrow" title={t("Settings")}>
      <SettingsLookProvider value="screen">
        <SettingsHostContext.Provider value={PORTAL_HOST}>
          <Suspense fallback={null}>
            <SettingsTabs />
          </Suspense>
        </SettingsHostContext.Provider>
      </SettingsLookProvider>
    </PageShell>
  );
}
