"use client";

import { useEffect, useState, type ReactNode } from "react";

import { useTranslation } from "@enode/core/translations/hooks";
import {
  setRestCountdownMode,
  useRestCountdownMode,
} from "@enode/core/training/flags";
import { UserValueMark } from "@enode/ui/user-value-mark";

// Top-of-view stats: the focus metric and a rest timer.
//
// Rest timer modes:
//   - count-up (default): elapsed seconds since the last completed
//     set, today's behaviour. Used when no target is available
//     (aiRestGuidance off, no frequency normative).
//   - countdown: max(0, target − elapsed), rendered in destructive
//     red once it hits 0. Used when `targetRestSec` is non-null AND
//     the localStorage-backed countdown-mode flag is on.
//
// `restSinceMs` is null until a set has been completed; that's also
// when the countdown is purely a display of the target value (nothing
// ticking yet). `targetRestSec` always renders bracketed in the cell
// header label so the coach sees the prescribed / estimated rest at a
// glance regardless of mode. Tapping the rest cell flips the
// countdown / count-up mode (the flag persists in localStorage); the
// tap is suppressed when no target exists.
//
// `onFocusTap` makes the focus cell interactive — used by
// ExerciseDetailView to open the 1RM edit sheet (for a weightlifting lift,
// since 17.11.26, the cell shows the PB and opens the exercise PB sheet).
// `focusValueUser` is the
// focus measurement's `valueUser`: when a person entered / overrode the
// value, a small corner tick (`UserValueMark`) sits at the top left of the
// value, in front of it.
export function SessionStats({
  header,
  focusLabel,
  focusValue,
  focusValueLoading,
  focusUnit,
  focusPrefix,
  focusValueUser,
  focusHint,
  onFocusTap,
  restSinceMs,
  targetRestSec,
}: {
  // Optional row rendered inside the card, above the 1RM/timer cells (used by
  // the active tracking view for the exercise name + athlete).
  header?: ReactNode;
  focusLabel: string;
  focusValue: string;
  // When true the focus value has no defined reading yet (e.g. an rm1 whose
  // value + valueUser are both the UNDEFINED sentinel) — render a skeleton in
  // place of the number rather than the sentinel.
  focusValueLoading?: boolean;
  focusUnit: string;
  // Small muted label rendered immediately before `focusValue` (e.g.
  // "BW" for Bodyweight-equipment exercises where the 1RM displays as
  // a delta from bodyweight). Same muted style as `unit`.
  focusPrefix?: string | null;
  // The focus measurement's `valueUser` (pass it only for the editable 1RM /
  // PB stat). Set → the override tick; unset or omitted → no mark.
  focusValueUser?: number | null;
  // 18.11.26 (audit C): a quiet hint in place of the value when there is no
  // reading to show — "Enter a PB" for a lift without one. Tappable only with
  // `onFocusTap`, like the value.
  focusHint?: string | null;
  onFocusTap?: () => void;
  restSinceMs: number | null;
  // Prescribed or AI-estimated target rest period in seconds. Null
  // when no target is available (aiRestGuidance off + no frequency
  // normative). Drives the countdown render and the bracketed label.
  targetRestSec: number | null;
}) {
  const elapsedSec = useElapsedSeconds(restSinceMs);
  const { t } = useTranslation();
  const countdownMode = useRestCountdownMode();

  // Before any set has been completed there's nothing to rest from —
  // hide the bracketed target, force the display to 00:00, and skip
  // the tap toggle. The target / mode logic only kicks in once a set
  // lands and the timer actually starts.
  const hasCompletedSet = restSinceMs != null;
  const hasTarget = hasCompletedSet && targetRestSec != null;
  const countdownActive = hasTarget && countdownMode;
  const displaySec = !hasCompletedSet
    ? 0
    : countdownActive
      ? Math.max(0, targetRestSec - elapsedSec)
      : elapsedSec;
  const displayTone =
    countdownActive && displaySec === 0 ? "destructive" : undefined;

  const restLabel = hasTarget
    ? `${t("Rest timer")} (${formatElapsed(targetRestSec)})`
    : t("Rest timer");

  // Only wire the tap when there's something to toggle to / from.
  // Without a completed set + target there's no countdown mode to
  // enter — the tap would silently change a flag with no visible
  // effect.
  const onRestTap = hasTarget
    ? () => setRestCountdownMode(!countdownMode)
    : undefined;

  return (
    <div className="rounded-2xl border border-surface-stroke bg-surface-base p-2.5 shadow-prominent">
      {header && (
        <div className="mb-2.5 border-b border-surface-stroke px-1.5 pb-2.5">
          {header}
        </div>
      )}
      {/* Explicit hairline between the two cells rather than `divide-x`: the
          focus cell is a button with negative side margins (`-mx-2`) for its
          hover bleed, which pulls a `divide-x` border off-centre and makes it
          read as a broken line. A standalone self-stretched 1px rule is
          independent of the cells' margins and matches the header divider
          (`border-surface-stroke`) exactly. */}
      <div className="flex items-stretch">
        <StatCell
          label={focusLabel}
          value={focusValue}
          loading={focusValueLoading}
          unit={focusUnit}
          prefix={focusPrefix ?? null}
          hint={focusHint ?? null}
          onClick={onFocusTap}
          valueMark={
            // Top left of the value: aligned to the line top and nudged to
            // the digits' top edge; the negative margin pulls it to the number.
            <UserValueMark
              valueUser={focusValueUser}
              ariaLabel={t("User-overridden value")}
              className="-mr-1 mt-[0.2em] self-start"
            />
          }
        />
        <div aria-hidden className="w-px shrink-0 self-stretch bg-surface-stroke" />
        <StatCell
          label={restLabel}
          value={formatElapsed(displaySec)}
          onClick={onRestTap}
          valueTone={displayTone}
        />
      </div>
    </div>
  );
}

function StatCell({
  label,
  value,
  loading,
  unit,
  prefix,
  hint,
  onClick,
  valueMark,
  valueTone,
}: {
  label: string;
  value: string;
  // Render a skeleton placeholder instead of the value (no defined reading).
  loading?: boolean;
  unit?: string;
  prefix?: string | null;
  // A quiet hint in place of the value (no reading, nothing loading).
  hint?: string | null;
  onClick?: () => void;
  // Rendered in front of the value (the override tick, top left).
  valueMark?: ReactNode;
  // "destructive" swaps the value text colour to the red used by
  // set-end criteria / invalid badges across the app. Default = no
  // override (inherits the cell's foreground).
  valueTone?: "destructive";
}) {
  const valueClass =
    valueTone === "destructive" ? "text-feedback-error" : "";
  const content = (
    <>
      <p className="stat-small uppercase tracking-wide text-foreground-muted">
        {label}
      </p>
      {loading ? (
        // A pulsing bar sized to the large digits — placeholder until a reading
        // (auto value or user override) lands.
        <span
          aria-label={value || undefined}
          className="stat-large-digits mt-1 block h-[1em] w-24 animate-pulse rounded-md bg-surface-base-muted"
        />
      ) : hint ? (
        // Sized like the digits' line so the card keeps its height; muted,
        // as a placeholder.
        <p className="stat-large-digits mt-1 flex items-center">
          <span className="body-small font-normal text-foreground-muted">
            {hint}
          </span>
        </p>
      ) : (
        <p
          className={`stat-large-digits mt-1 flex items-baseline gap-1.5 ${valueClass}`}
        >
          {valueMark}
          {prefix && (
            <span className="heading-small uppercase text-foreground-muted">
              {prefix}
            </span>
          )}
          {value}
          {unit && (
            <span className="heading-small uppercase text-foreground-muted">
              {unit}
            </span>
          )}
        </p>
      )}
    </>
  );
  if (onClick) {
    return (
      <button
        type="button"
        onClick={onClick}
        className="-mx-2 flex flex-1 flex-col items-center justify-center rounded-lg px-4 py-1 transition-colors hover:bg-surface-base-muted"
      >
        {content}
      </button>
    );
  }
  return (
    <div className="flex flex-1 flex-col items-center justify-center px-4">
      {content}
    </div>
  );
}

function useElapsedSeconds(sinceMs: number | null): number {
  const [now, setNow] = useState(() => Date.now());

  // Timer effect: Date.now() must be read outside render, so re-baselining
  // `now` when sinceMs changes is a genuine in-effect setState.
  /* eslint-disable react-hooks/set-state-in-effect */
  useEffect(() => {
    if (sinceMs == null) return;
    setNow(Date.now());
    const interval = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(interval);
  }, [sinceMs]);
  /* eslint-enable react-hooks/set-state-in-effect */

  if (sinceMs == null) return 0;
  return Math.max(0, Math.floor((now - sinceMs) / 1000));
}

function formatElapsed(sec: number): string {
  const safe = Math.max(0, Math.floor(sec));
  const mm = String(Math.floor(safe / 60)).padStart(2, "0");
  const ss = String(safe % 60).padStart(2, "0");
  return `${mm}:${ss}`;
}
