"use client";

import { useEffect, useMemo, useState } from "react";
import type { SessionReturnDto } from "@enode/core/api/dtos/sessions";
import { getExerciseSessionsBefore } from "@enode/core/api/sessions";
import {
  metricCategoryColor,
  type MetricCategoryKey,
} from "@enode/core/metrics/category-colors";
import { getMetric } from "@enode/core/metrics/store";
import {
  STAT_KEYS,
  statValue,
  summarizeSession,
  trendPct,
  type StatKey,
} from "@enode/core/training/exercise-overview";
import { useLoadingContext } from "@enode/core/training/loading-context";
import { useTranslation } from "@enode/core/translations/hooks";
import { useUnits } from "@enode/core/use-units";
import { MetricStatCard } from "@enode/ui/metric-stat-card";
import { SessionsTable } from "./sessions-table";
import { SummarySectionHeader } from "./summary-glance";
import { useSessionMetrics } from "./use-session-metrics";

// Session drawer → History tab: the viewed (completed) session's metrics as
// stat cards (each with a trend + sparkline across the sessions of the same
// exercise that PRECEDE it), then those sessions in the sessions table. Portal
// analogue of the tracking app's in-training Overview tab — here the "current"
// session is the completed one being viewed (not a live training session), so
// its comparison set is anchored to its own date rather than to today.

// Reversible: style the summary stat cards like the Technique line-chart header
// — a `heading-section` label, a big metric-coloured value, and a green/red
// trend badge. Flip to false for the original muted-label / neutral-value cards.
const TECHNIQUE_CARD_STYLE = true;

const STAT_KIND: Record<StatKey, "load" | "count" | "time"> = {
  oneRm: "load",
  volumeLoad: "load",
  highestLoad: "load",
  totalReps: "count",
  sets: "count",
  avgRestSeconds: "time",
  totalTimeSeconds: "time",
};

// Each stat is tinted by its metric category (loads → "loading", counts →
// "number", durations → "time"); the +/− sign conveys trend direction.
const KIND_CATEGORY: Record<"load" | "count" | "time", MetricCategoryKey> = {
  load: "loading",
  count: "number",
  time: "time",
};

const STAT_LABELS: Record<
  StatKey,
  (t: ReturnType<typeof useTranslation>["t"]) => string
> = {
  oneRm: (t) => t("1RM"),
  volumeLoad: (t) => t("Volume load"),
  highestLoad: (t) => t("Highest load"),
  totalReps: (t) => t("Total reps"),
  sets: (t) => t("Sets"),
  avgRestSeconds: (t) => t("Avg. rest period"),
  totalTimeSeconds: (t) => t("Total time"),
};

function formatDuration(totalSeconds: number): string {
  const s = Math.max(0, Math.round(totalSeconds));
  const h = Math.floor(s / 3600);
  const m = Math.floor((s % 3600) / 60);
  const sec = s % 60;
  const mm = String(m).padStart(2, "0");
  const ss = String(sec).padStart(2, "0");
  return h > 0 ? `${h}:${mm}:${ss}` : `${mm}:${ss}`;
}

// Compact numeric axis label for the detailed trend chart — day/month ordered
// per locale (e.g. "22/10" or "10/22"), no year.
function shortDate(ms: number | null): string {
  if (ms == null) return "";
  const d = new Date(ms);
  if (Number.isNaN(d.getTime())) return "";
  return d.toLocaleDateString(undefined, { day: "2-digit", month: "2-digit" });
}

type LoadStatus = "loading" | "ready" | "error";

export function SessionSummaryTab({
  session,
  onOpenSession,
}: {
  session: SessionReturnDto;
  // Accepted for tab-API symmetry; the summary reads set-level measurements
  // (present on the base session), so it doesn't wait on the rep-level load.
  loading?: boolean;
  // Open an earlier session in a (stacked) session drawer — wired to the
  // sessions table's row click, so the drawer stacks at this one's depth + 1.
  onOpenSession?: (session: SessionReturnDto) => void;
}) {
  const { t } = useTranslation();
  const units = useUnits();

  // Exercise-type + equipment aware metric selection: the focus metric (1RM /
  // peak force / top load / jump height, resolved from the exercise group via
  // the session's definition → catalogue exercise → base) and whether the load
  // is mass or inertia (from the session's measurements — gates volume). The
  // viewed session's exercise drives this; its history is the same exercise, so
  // one resolution covers the whole tab.
  const { resolve } = useSessionMetrics();
  const {
    ids,
    focusKey,
    isInertia,
    loadingDimension,
    focusDimension,
  } = resolve(session);

  // Volume-load (mass) + count units for the remaining stat cards.
  const loadDimension = getMetric(ids.loadingMass)?.dimension ?? null;
  const countDimension = getMetric(ids.repCount)?.dimension ?? "count";

  // Bodyweight-equipment exercises display per-set loads and the 1RM as a
  // delta from the athlete's bodyweight ("BW +5 kg"), same as the tracking
  // app. Resolved from the viewed session's athlete + exercise; the history
  // is the same exercise instance (same athlete), so one context covers all.
  const loadingCtx = useLoadingContext(
    session.user?.id ? { userID: session.user.id } : null,
    session.exercise ?? null,
  );

  // The first (focus) card and the highest-load card carry exercise-type labels;
  // volume load drops out entirely for inertia (flywheel) exercises.
  const focusLabel =
    focusKey === "forcePeak"
      ? t("Peak force")
      : focusKey === "loadingMass"
        ? t("Highest load")
        : focusKey === "jumpHeight"
          ? t("Jump height")
          : t("1RM");
  const highestLoadLabel = isInertia
    ? t("Highest inertia")
    : t("Highest load");
  // A weightlifting session's focus metric IS the top load, so its focus card
  // already reads "Highest load"; the per-set card would say it a second time
  // (G-21, 17.11.26). The focus card goes: the per-set one is computed from
  // the sets on screen and follows an edit right away.
  const statKeys = STAT_KEYS.filter(
    (k) =>
      !(isInertia && k === "volumeLoad") &&
      !(focusKey === "loadingMass" && k === "oneRm"),
  );

  // The history endpoint keys off the per-user exercise INSTANCE id (which
  // carries the athlete), not the shared definition id.
  const exerciseID = session.exerciseID ?? session.exercise?.id ?? null;
  const userID = session.user?.id ?? null;
  // Reviewing a session means comparing it against what came BEFORE it, so the
  // history is cut off at the viewed session's own timestamp — otherwise an
  // older session is shown against sessions that happened after it, and its
  // trend badges read backwards. The −1 ms keeps the cutoff exclusive, so the
  // viewed session isn't one of the five returned. Undefined (no `created`)
  // leaves the endpoint at its default: the five most recent.
  const before = session.created != null ? session.created - 1 : undefined;
  const [history, setHistory] = useState<SessionReturnDto[]>([]);
  const [status, setStatus] = useState<LoadStatus>(
    exerciseID && userID ? "loading" : "ready",
  );
  const [reloadKey, setReloadKey] = useState(0);

  useEffect(() => {
    if (!exerciseID || !userID) return;
    let cancelled = false;
    getExerciseSessionsBefore(userID, exerciseID, before)
      .then((sessions) => {
        if (cancelled) return;
        setHistory(sessions);
        setStatus("ready");
      })
      .catch((err) => {
        if (cancelled) return;
        console.error("Failed to load exercise history:", err);
        setStatus("error");
      });
    return () => {
      cancelled = true;
    };
  }, [userID, exerciseID, before, reloadKey]);

  // Recent sessions (incl. the viewed one), deduped by id with the viewed
  // session winning its own row (it carries the full set tree), chronological.
  const byId = new Map<string, SessionReturnDto>();
  for (const s of history) if (s.id) byId.set(s.id, s);
  byId.set(session.id, session);
  const ordered = [...byId.values()]
    .map((s) => ({ session: s, summary: summarizeSession(s, ids) }))
    .sort((a, b) => (a.summary.date ?? 0) - (b.summary.date ?? 0));

  const currentSummary = summarizeSession(session, ids);
  // The viewed session's slot in the charts (it is one of `ordered`).
  const viewedIndex = ordered.findIndex((x) => x.session.id === session.id);
  const seriesFor = (key: StatKey) => ordered.map((x) => statValue(x.summary, key));

  // Format one stat value with its unit. Time stats render as a duration; the
  // others go through the active unit system with the stat's dimension. Used for
  // both the card's headline value and each labelled point on the trend chart.
  const formatStat = (
    key: StatKey,
    value: number | null,
  ): { text: string; unit: string | null } => {
    if (value == null) return { text: "—", unit: null };
    const kind = STAT_KIND[key];
    if (kind === "time") return { text: formatDuration(value), unit: null };
    const dim =
      kind === "count"
        ? countDimension
        : key === "oneRm"
          ? focusDimension
          : key === "highestLoad"
            ? loadingDimension
            : loadDimension;
    const f = units.format(value, dim);
    return { text: f.text ?? "—", unit: f.unit };
  };

  // The card's HEADLINE value: like `formatStat`, but the per-set mass loads
  // (focus 1RM / highest load) render bodyweight-relative under a bodyweight
  // context. Volume load stays absolute (a Σ is not a load). Trend-axis ticks
  // keep `formatStat` — the plotted series is absolute.
  const headlineStat = (
    key: StatKey,
    value: number | null,
  ): { text: string; unit: string | null; prefix: string | null } => {
    const dim =
      key === "oneRm"
        ? focusDimension
        : key === "highestLoad"
          ? loadingDimension
          : null;
    if (
      value != null &&
      dim === "mass" &&
      loadingCtx.mode === "bodyweight" &&
      (key === "oneRm" || key === "highestLoad")
    ) {
      const f = units.formatLoad(value, dim, loadingCtx);
      return {
        text: f.text ? `${f.sign}${f.text}` : "—",
        unit: f.unit,
        prefix: t("BW"),
      };
    }
    return { ...formatStat(key, value), prefix: null };
  };

  // The other recent sessions (newest first, deduped by id) — the viewed one is
  // the headline, so it's excluded from the earlier-sessions table. Memoized:
  // the table resets its row overrides whenever it gets a new `sessions` array.
  const earlierSessions = useMemo(() => {
    const earlier = new Map<string, SessionReturnDto>();
    for (const s of history) {
      if (s.id && s.id !== session.id) earlier.set(s.id, s);
    }
    return [...earlier.values()].sort(
      (a, b) => (b.created ?? 0) - (a.created ?? 0),
    );
  }, [history, session.id]);

  return (
    // Adaptive to the DRAWER width, not the viewport: the session drawer is
    // resizable, so a wide window with a thin drawer must still read well.
    // `@container` makes the `@[…]` breakpoints below measure this wrapper
    // (≈ the drawer's content width) instead of the screen. One column at every
    // width — the stat cards on top (2 columns, 3 from 42rem, 4 from 96rem),
    // the earlier sessions below as the full-width sessions table, which needs
    // the width a side column couldn't give it.
    <div className="@container mx-auto w-full max-w-[150rem]">
      <div className="grid gap-y-8">
        <section className="min-w-0">
          <SummarySectionHeader
            title={t("This session")}
            aside={
              status === "ready" && earlierSessions.length > 0
                ? t(
                    "{count, plural, one {Trend across # earlier session} other {Trend across # earlier sessions}}",
                    { count: earlierSessions.length },
                  )
                : null
            }
          />
          <div className="mt-3 grid grid-cols-2 gap-3 @[42rem]:grid-cols-3 @[96rem]:grid-cols-4">
            {statKeys.map((key) => {
              const series = seriesFor(key);
              const current = headlineStat(key, statValue(currentSummary, key));
              // One point per session for the detailed chart: its raw value (the
              // chart formats the y-axis ticks) and a short date for the x-axis.
              const trendPoints = ordered.map(({ summary }) => ({
                value: statValue(summary, key),
                dateLabel: shortDate(summary.date),
              }));

              // The focus card and highest-load card carry exercise-type labels;
              // the rest use their static label.
              const label =
                key === "oneRm"
                  ? focusLabel
                  : key === "highestLoad"
                    ? highestLoadLabel
                    : STAT_LABELS[key](t);

              return (
                <div key={key} className="grid min-w-0">
                  <MetricStatCard
                    label={label}
                    value={current.text}
                    unit={current.unit}
                    valuePrefix={current.prefix}
                    trendPct={trendPct(series)}
                    series={series}
                    color={metricCategoryColor(KIND_CATEGORY[STAT_KIND[key]])}
                    trendPoints={trendPoints}
                    formatTrendValue={(v) => formatStat(key, v).text}
                    variant={TECHNIQUE_CARD_STYLE ? "technique" : "default"}
                    // One bar per session; the viewed one in full colour,
                    // the sessions before it a step back.
                    chart="bars"
                    highlightIndex={viewedIndex >= 0 ? viewedIndex : undefined}
                    chartLoading={status === "loading"}
                  />
                </div>
              );
            })}
          </div>
        </section>

        {/* The same exercise's sessions leading up to the viewed one, in the
            portal's sessions table. Athlete and exercise are the same on every
            row, so those columns go; a row opens that session in a drawer
            stacked over this one. */}
        <section className="min-w-0">
          <SummarySectionHeader title={t("Earlier sessions")} />
          <div className="mt-3">
            {status === "error" ? (
              <div className="space-y-2 py-6 text-center">
                <p className="body-small text-feedback-error">
                  {t("Couldn't load recent sessions.")}
                </p>
                <button
                  type="button"
                  onClick={() => {
                    setStatus("loading");
                    setReloadKey((k) => k + 1);
                  }}
                  className="clickable-small rounded-full border border-surface-stroke px-4 py-1.5 text-foreground-default hover:bg-surface-base-muted"
                >
                  {t("Try again")}
                </button>
              </div>
            ) : (
              <SessionsTable
                sessions={earlierSessions}
                loading={status === "loading"}
                emptyMessage={t("No previous sessions yet")}
                hideAthlete
                hideExercise
                flat
                onOpenSession={onOpenSession}
              />
            )}
          </div>
        </section>
      </div>
    </div>
  );
}
