"use client";

import { Suspense, useEffect, useState, type ReactNode } from "react";
import { useRouter } from "next/navigation";
import {
  completeSignIn,
  discardRedeemedHandoff,
  logout,
  OtherAccountOfflineDataError,
  redeemPortalHandoffCode,
  releaseDeviceSession,
  startRedeemedSession,
  type RedeemedHandoff,
} from "@enode/core/api/auth";
import type { AccessTokenResponseDto } from "@enode/core/api/dtos/auth";
import { getCurrentUserID, getToken } from "@enode/core/api/storage";
import { otherAccountUnsyncedData } from "@enode/core/offline/owner";
import {
  getCurrentUserSnapshot,
  loadCurrentUser,
} from "@enode/core/current-user/store";
import { useTranslation } from "@enode/core/translations/hooks";
import { ProductGuidanceLoader } from "@enode/core/tours/ProductGuidanceLoader";
import { ConfirmDialog } from "@enode/ui/confirm-dialog";
import { presentError } from "@enode/ui/feedback/use-error-presenter";
import { MetricKeyboardProvider } from "@enode/ui/metric-keyboard/MetricKeyboardProvider";
import { TourProvider } from "@enode/ui/tour/tour-provider";
import { AppShell } from "../../components/app-shell";
import { NotOnADisplay } from "../../components/not-on-a-display";
import { NotificationArrivalPeek } from "../../components/notifications/notification-arrival-peek";
import { NotificationStreamHost } from "@enode/ui/notifications/notification-stream-host";
import { RosterProgressPeek } from "../../components/roster-progress/roster-progress-peek";
import { RosterProgressStreamHost } from "../../components/roster-progress/roster-progress-stream-host";
import { MockOverridesLoader } from "./debug/mock-overrides";
import { HandoffCard } from "./handoff-card";
import { HandoffArrivalLine } from "../../components/notices/handoff-arrival-line";
import { decideHandoff, stripHandoffParam, type HandoffRedeemResult } from "../handoff-decision";
import { rememberPortalReturnTo, takeHandoffCode } from "../return-to";

// A code is single-use, and React runs an effect twice in development: both
// runs share one request, or the second would be refused and bounce a user who
// was just signed in. Redeeming does NOT start a session — whose account it is
// gets checked first — and runs under a temporary device id, so the session
// signed in here survives it.
const redeeming = new Map<string, Promise<RedeemedHandoff>>();
function redeemOnce(code: string): Promise<RedeemedHandoff> {
  let pending = redeeming.get(code);
  if (!pending) {
    pending = redeemPortalHandoffCode(code);
    redeeming.set(code, pending);
  }
  return pending;
}

// The code taken off the address, shared by both development effect runs: run 1
// strips `?handoff` and is cancelled, so run 2 would otherwise read a clean URL,
// render the current account's portal and leave the other account's code spent.
// Cleared once a run has applied the decision.
let takenHandoff: { code: string | null; path: string } | null = null;

/** sessionStorage key of the one-shot "you arrived from the app" line. */
const HANDOFF_ARRIVAL_KEY = "enode.handoffArrival";

function rememberHandoffArrival(name: string, signedOutName?: string): void {
  try {
    window.sessionStorage.setItem(
      HANDOFF_ARRIVAL_KEY,
      JSON.stringify(signedOutName ? { name, signedOutName } : { name }),
    );
  } catch {
    // Storage unavailable: no arrival line, nothing else depends on it.
  }
}

function redeemedName(response: AccessTokenResponseDto): string {
  return response.user?.name || response.user?.email || "";
}

async function currentUserName(): Promise<string> {
  try {
    await loadCurrentUser();
  } catch {
    // Name unknown: the prompt still works with an empty name.
  }
  const user = getCurrentUserSnapshot();
  return user?.name || user?.email || "";
}

// What the layout shows while a link from the app is reconciled with the
// session already here. Nothing but `ready` renders the dashboard.
type ConfirmSwitchPhase = {
  kind: "confirmSwitch";
  response: RedeemedHandoff;
  redeemedName: string;
  currentName: string;
};

type Phase =
  | { kind: "pending" }
  | { kind: "ready" }
  | ConfirmSwitchPhase
  | { kind: "redeemFailedSignedIn"; currentName: string }
  | {
      kind: "confirmDiscard";
      error: OtherAccountOfflineDataError;
      signedOutName?: string;
      /** Cancel returns here (asked while the current account is still signed in). */
      backTo?: ConfirmSwitchPhase;
    };

// Auth-gated shell for the authenticated portal area. Bounces to the login
// screen without a token, otherwise renders pages inside the sidebar shell.
export default function DashboardLayout({ children }: { children: ReactNode }) {
  const { t } = useTranslation();
  const router = useRouter();
  const [phase, setPhase] = useState<Phase>({ kind: "pending" });
  const [busy, setBusy] = useState(false);
  const [returnPath, setReturnPath] = useState("/dashboard");

  const toSignIn = (path: string) => {
    // Come back here after the sign-in.
    rememberPortalReturnTo(path);
    router.replace("/");
  };

  // Starts the redeemed account's session; another account's unsynced
  // offline data is asked about first, exactly like the OTP sign-in does.
  const beginRedeemed = async (
    response: RedeemedHandoff,
    path: string,
    signedOutName?: string,
  ): Promise<void> => {
    try {
      await startRedeemedSession(response);
    } catch (err) {
      if (err instanceof OtherAccountOfflineDataError) {
        setPhase({ kind: "confirmDiscard", error: err, signedOutName });
      } else {
        // The token may already be stored: never leave a half-started session.
        logout();
        toSignIn(path);
      }
      return;
    }
    rememberHandoffArrival(redeemedName(response), signedOutName);
    setPhase({ kind: "ready" });
  };

  /* eslint-disable react-hooks/set-state-in-effect */
  useEffect(() => {
    // A link from the tracking app may carry a one-time sign-in code. It is
    // taken off the address at once, then ALWAYS redeemed — also when someone
    // is signed in here, so a different person is never shown silently.
    takenHandoff ??= takeHandoffCode(
      window.location.pathname + window.location.search,
    );
    const { code, path } = takenHandoff;
    setReturnPath(path);
    if (!code) {
      takenHandoff = null;
      if (getToken()) setPhase({ kind: "ready" });
      else toSignIn(path);
      return;
    }
    window.history.replaceState(
      window.history.state,
      "",
      stripHandoffParam(window.location.href),
    );
    let cancelled = false;
    void (async () => {
      let response: RedeemedHandoff | null = null;
      try {
        response = await redeemOnce(code);
      } catch {
        // Expired, used, or no portal access.
      }
      if (cancelled) return;
      const redeem: HandoffRedeemResult =
        response?.token && response.user?.id
          ? { ok: true, userId: response.user.id, name: redeemedName(response) }
          : { ok: false };
      const currentUserId = getToken() ? getCurrentUserID() : null;
      const currentName = currentUserId ? await currentUserName() : "";
      if (cancelled) return;
      const decision = decideHandoff({ currentUserId, currentName, redeem });
      takenHandoff = null;
      switch (decision.kind) {
        case "startRedeemed":
          if (response) await beginRedeemed(response, path);
          return;
        case "keepCurrent":
          // Same person: the redeemed session is simply dropped.
          if (response) discardRedeemedHandoff(response);
          setPhase({ kind: "ready" });
          return;
        case "confirmSwitch":
          if (response) setPhase({ ...decision, response });
          return;
        case "redeemFailedSignedIn":
          setPhase(decision);
          return;
        case "redeemFailedSignedOut":
          toSignIn(path);
          return;
      }
    })();
    return () => {
      cancelled = true;
    };
    // toSignIn / beginRedeemed only use the stable router and state setters.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [router]);
  /* eslint-enable react-hooks/set-state-in-effect */

  if (phase.kind === "confirmSwitch") {
    const switchPhase = phase;
    const { response, currentName } = phase;
    const name = phase.redeemedName;
    return (
      <HandoffCard
        title={t("Continue as {name}?", { name })}
        primaryLabel={t("Continue as {name}", { name })}
        onPrimary={() => {
          setBusy(true);
          void (async () => {
            // Ask about another account's offline data while the current
            // account is still signed in, so Cancel leaves it untouched.
            const unsynced = response.user?.id
              ? await otherAccountUnsyncedData(response.user.id)
              : null;
            if (unsynced) {
              setPhase({
                kind: "confirmDiscard",
                error: new OtherAccountOfflineDataError(unsynced, response),
                signedOutName: currentName,
                backTo: switchPhase,
              });
              return;
            }
            // End the current account's server session too (best effort).
            await releaseDeviceSession();
            logout();
            await beginRedeemed(response, returnPath, currentName);
          })()
            .catch((err: unknown) => {
              // Still signed in (the offline-data check failed): stay on the
              // card and say why. Already signed out: go to the sign-in.
              if (getToken()) presentError(err, t);
              else toSignIn(returnPath);
            })
            .finally(() => setBusy(false));
        }}
        secondaryLabel={
          currentName
            ? t("Stay as {name}", { name: currentName })
            : t("Stay signed in")
        }
        onSecondary={() => {
          discardRedeemedHandoff(response);
          setPhase({ kind: "ready" });
        }}
        busy={busy}
      />
    );
  }

  if (phase.kind === "redeemFailedSignedIn") {
    const { currentName } = phase;
    return (
      <HandoffCard
        title={
          currentName
            ? t("You're signed in here as {name}", { name: currentName })
            : t("You're already signed in here.")
        }
        primaryLabel={t("Sign out and continue")}
        onPrimary={() => {
          logout();
          toSignIn(returnPath);
        }}
        secondaryLabel={
          currentName
            ? t("Stay as {name}", { name: currentName })
            : t("Stay signed in")
        }
        onSecondary={() => setPhase({ kind: "ready" })}
      />
    );
  }

  if (phase.kind === "confirmDiscard") {
    const { error, signedOutName, backTo } = phase;
    return (
      // Same prompt and copy as the OTP sign-in (auth-steps.tsx).
      <ConfirmDialog
        open
        title={t("Delete another account's data?")}
        message={t(
          "This device holds training data from another account that hasn't been uploaded yet ({workouts, plural, =0 {} one {# workout, } other {# workouts, }}{videos, plural, =0 {no videos} one {# video} other {# videos}}{answers, plural, =0 {} one {, # check-in or session rating} other {, # check-ins or session ratings}}). Signing in with this account deletes it. To keep it, cancel and sign in with the other account first so it can upload.",
          {
            workouts: error.unsynced.uploads + error.unsynced.activeTrainings,
            videos: error.unsynced.videos,
            answers: error.unsynced.questionnaires,
          },
        )}
        confirmLabel={t("Sign in and delete")}
        cancelLabel={t("Cancel")}
        destructive
        busy={busy}
        onConfirm={() => {
          setBusy(true);
          // Still signed in when asked before the switch: sign out only now.
          if (getToken()) logout();
          completeSignIn(error.response).then(
            () => {
              rememberHandoffArrival(redeemedName(error.response), signedOutName);
              setBusy(false);
              setPhase({ kind: "ready" });
            },
            () => {
              logout();
              setBusy(false);
              toSignIn(returnPath);
            },
          );
        }}
        onCancel={() => (backTo ? setPhase(backTo) : toSignIn(returnPath))}
      />
    );
  }

  if (phase.kind !== "ready") return null;

  return (
    <MetricKeyboardProvider>
      {/* Re-applies the debug "Mock data" switches to the stores on load, so a
          mocked page survives a reload without visiting /dashboard/debug first.
          No-ops in a production build. */}
      <MockOverridesLoader />
      {/* Not on a live session's display (`?present=`): a television has
          nobody to read a peek, and a tour never starts there. */}
      <NotOnADisplay>
        <NotificationStreamHost />
        <NotificationArrivalPeek />
        <RosterProgressStreamHost />
        <RosterProgressPeek />
        {/* Spotlight tours (sidebar + page targets) — pages start them via
            <TourAutoStart> / useTourController (see src/tours/). The loader
            hydrates which tours this user has already seen; until it settles
            no tour auto-starts. */}
        <ProductGuidanceLoader platform="portal" />
      </NotOnADisplay>
      <TourProvider>
        <AppShell>
          <HandoffArrivalLine />
          {/* Pages read their view from the address (url-state.ts), and
              `useSearchParams` needs a Suspense boundary in a static export. */}
          <Suspense fallback={null}>{children}</Suspense>
        </AppShell>
      </TourProvider>
    </MetricKeyboardProvider>
  );
}
