"use client";

import { useEffect, useRef, useState, type ReactNode } from "react";
import type { FocusMetricKey } from "@enode/core/coaching/session-focus-metric";
import { useTranslation } from "@enode/core/translations/hooks";
import type { LoadContextShape } from "@enode/core/units";
import type { WorkoutSession } from "@enode/core/training/models";
import { Sheet } from "@enode/ui/sheet";
import { ActionMenu } from "@enode/ui/action-menu";
import { ContentColumn } from "@enode/ui/content-column";
import { ScrollEdgeFade } from "@enode/ui/scroll-edge-fade";
import { HEADER_MIN_HEIGHT, HEADER_BLUR, headerEdgeClass } from "./header";
import { XIcon } from "./icons";
import { PerformanceTab } from "./performance-tab";
import type { SetRepsEdit } from "@enode/core/training/rep-edits";
import { RepsTab } from "./reps-tab";
import { TechniqueTab } from "./technique-tab";
import { useOwnDeviceSession } from "@enode/core/device-session/hooks";
import { LiveResultTab, useHasLiveResult } from "./live-result-card";
import { LiveTab } from "./live-tab";
import { OverviewTab } from "./overview-tab";
import { SegmentedPicker } from "@enode/ui/segmented-picker";
import { DetailsTab } from "./details-tab";
import type { SessionDetailsPatch } from "./session-details";
import { HEADER_ICON_BUTTON } from "@enode/ui/header-button";

export type InsightsTab =
  | "overview"
  | "reps"
  | "performance"
  | "technique"
  | "live"
  | "details";

// Width of the fade that says "there is more this way" at a clipped edge of
// the pill row.
const PILL_FADE_PX = 28;

/**
 * The tab pills in one row. The pills share the row's width while they fit
 * (each refuses to shrink below its label); where they do not, the row
 * scrolls sideways, fades at the edge that clips pills, and keeps the active
 * pill in view — so a pill that is off screen is never the selected one, and
 * the fade says that there are more.
 *
 * @param activeKey - Changes when another pill becomes the active one (the
 *   pill with `aria-pressed="true"` is brought into view).
 */
function TabPillRow({
  activeKey,
  count,
  children,
}: {
  activeKey: string;
  /** How many pills there are: the row is measured again when one joins. */
  count: number;
  children: ReactNode;
}) {
  const rowRef = useRef<HTMLDivElement>(null);
  // Which edges clip pills right now.
  const [clipped, setClipped] = useState({ start: false, end: false });

  useEffect(() => {
    const row = rowRef.current;
    if (!row) return;
    const measure = () => {
      const start = row.scrollLeft > 1;
      const end = row.scrollLeft + row.clientWidth < row.scrollWidth - 1;
      setClipped((prev) =>
        prev.start === start && prev.end === end ? prev : { start, end },
      );
    };
    measure();
    row.addEventListener("scroll", measure, { passive: true });
    if (typeof ResizeObserver === "undefined") {
      return () => row.removeEventListener("scroll", measure);
    }
    // The row's own width, and the pills' (a tab joins, a language changes).
    const ro = new ResizeObserver(measure);
    ro.observe(row);
    for (const pill of row.children) ro.observe(pill);
    return () => {
      row.removeEventListener("scroll", measure);
      ro.disconnect();
    };
  }, [count]);

  // The active pill in view, clear of the fade. Scrolled by hand: the row
  // alone moves, never the page around it.
  useEffect(() => {
    const row = rowRef.current;
    const active = row?.querySelector<HTMLElement>('[aria-pressed="true"]');
    if (!row || !active) return;
    const left = active.offsetLeft - row.offsetLeft;
    const right = left + active.offsetWidth;
    if (left - PILL_FADE_PX < row.scrollLeft) {
      row.scrollLeft = Math.max(0, left - PILL_FADE_PX);
    } else if (right + PILL_FADE_PX > row.scrollLeft + row.clientWidth) {
      row.scrollLeft = right + PILL_FADE_PX - row.clientWidth;
    }
  }, [activeKey, count]);

  const mask =
    clipped.start || clipped.end
      ? `linear-gradient(90deg, ${
          clipped.start ? `transparent, #000 ${PILL_FADE_PX}px` : "#000"
        }, ${
          clipped.end
            ? `#000 calc(100% - ${PILL_FADE_PX}px), transparent`
            : "#000"
        })`
      : undefined;

  return (
    <div
      ref={rowRef}
      data-testid="insights-tab-pills"
      style={{ maskImage: mask, WebkitMaskImage: mask }}
      className="scrollbar-none flex flex-nowrap gap-1.5 overflow-x-auto"
    >
      {children}
    </div>
  );
}

// Same names and order as the portal's session drawer: Performance first (the
// tab the sheet opens on), then Reps and Technique, the exercise's History
// ("overview"), and Details — the session's facts, tags and note — last.
// The ids stay "overview" and "reps" — they key the tabs' content and the rep
// list's edit callback, whatever the tabs are called.
const BASE_TABS: InsightsTab[] = ["performance", "reps", "technique", "overview", "details"];
// While the device is part of a live session a further tab carries the
// session's standings for the exercise on the bar — before History and
// Details, which stay last.
const LIVE_TABS: InsightsTab[] = [
  "performance",
  "reps",
  "technique",
  "live",
  "overview",
  "details",
];
// Feedback training: no History (its cards are about loads, 1RM and volume —
// a workout's numbers), no Live tab (no live session behind local sets) and no
// Details (its local sets are no session to describe).
const FEEDBACK_TABS: InsightsTab[] = ["performance", "reps", "technique"];

// Exercise insights. By default opens from the floating chart button in
// ExerciseDetailView as a bottom-up Sheet ("modal"). In trackingDetailMode
// (Settings) and when the hosting column has enough width, ExerciseDetailView
// renders this in `inline` mode instead — the body sits in a side pane
// alongside the tracking view with no Sheet wrapper and no close button.
export function InsightsSheet({
  open,
  onClose,
  session,
  exerciseGroupID,
  equipmentGroupID,
  loadingCtx,
  exerciseBaseID,
  isBarbell = false,
  onFlipRep,
  onRepsChange,
  renderMode = "modal",
  initialTab = "performance",
  feedback = false,
  detailsHeader = null,
  repsLoadShare = null,
  onSessionChange,
}: {
  open: boolean;
  onClose: () => void;
  session?: WorkoutSession;
  exerciseGroupID?: string | null;
  // The exercise's equipment group — lets the History tab resolve the session
  // focus metric + the loading metric (inertia vs mass) for flywheel.
  equipmentGroupID?: string | null;
  // Load display semantics for the History tab (absolute vs "BW ±delta" for
  // Bodyweight-equipment exercises) — resolved once by ExerciseDetailView.
  loadingCtx?: LoadContextShape;
  exerciseBaseID?: string | null;
  // Bar-path / trajectory chart is only meaningful for barbell-equipment-group
  // exercises; gates it in the Technique tab.
  isBarbell?: boolean;
  // Flip the currently-shown Technique rep's trajectory, recalculating its
  // stored raw data (see `flipRepInSession`). Omitted when no session owner can
  // persist the change; the flip menu item hides.
  onFlipRep?: (repId: string) => void;
  // Commit rep-list edits (validity toggle / deletion) made in the Reps tab.
  // Its selection spans sets, so several sets can arrive at once and must be
  // applied together. Omitted when no session owner can persist the change; the
  // tab's rows then stay read-only, as `onFlipRep` gates the flip.
  onRepsChange?: (edits: readonly SetRepsEdit[]) => void;
  renderMode?: "modal" | "inline";
  // The tab the sheet opens on (every time it opens). Feedback training opens
  // straight on Reps, since a tapped set is what the coach wants to read.
  // Falls back to the first tab when `feedback` leaves it out.
  initialTab?: InsightsTab;
  // Feedback training's local sets: there is no workout and no load, so the
  // sheet shows only Performance, Reps and Technique, and nothing
  // load-dependent (force, power, … — the metric's `loadingFactor` flag)
  // appears in any of them. The session handed in should already carry no
  // load-dependent measurements (`feedbackInsightsSession`); this also drops
  // what the tabs derive or pick on their own. The sets are only read: the
  // Reps tab's selection can delete reps but not tag or invalidate them.
  feedback?: boolean;
  // The Details tab's facts-card header — the exercise + athlete switchers,
  // passed only by the modal sheet (the iPad side pane sits beside the
  // tracking header, which shows them already).
  detailsHeader?: ReactNode;
  // The 1RM (a lift's PB) the Reps tab states each set's load against, under
  // the load. Omitted (the feedback flow): no share.
  repsLoadShare?: { rm1: number | null; focusKey: FocusMetricKey | null } | null;
  // Commit a Details-tab edit (note, session tags) to the session. Omitted
  // when no session owner can persist the change; the tab is then read-only.
  onSessionChange?: (patch: SessionDetailsPatch) => void;
}) {
  const inline = renderMode === "inline";
  const [tab, setTab] = useState<InsightsTab>(initialTab);
  const [prevOpen, setPrevOpen] = useState(open);
  const { t } = useTranslation();
  const isLive = useOwnDeviceSession()?.workoutLiveSessionID != null;
  // After a session has ended the tab stays for its result, until the next
  // day (live-result-card.tsx).
  const hasLiveResult = useHasLiveResult();
  const hasLiveTab = !feedback && (hasLiveResult || isLive);
  const TABS = feedback ? FEEDBACK_TABS : hasLiveTab ? LIVE_TABS : BASE_TABS;
  // A tab this sheet doesn't offer (the live session ended while its tab was
  // open, or an opening tab feedback leaves out) falls back to the first tab.
  const shownTab: InsightsTab = TABS.includes(tab) ? tab : TABS[0];
  // The rep the Technique tab is currently showing, reported up so the header
  // "…" menu's "Flip trajectory data" acts on it (a per-rep data recalculation
  // via `onFlipRep`, not a render-only toggle).
  const [techniqueRepId, setTechniqueRepId] = useState<string | undefined>(
    undefined,
  );

  // Reset to the opening tab each time the sheet opens.
  if (open !== prevOpen) {
    setPrevOpen(open);
    if (open) setTab(initialTab);
  }

  // The header + tabs render as a frosted OVERLAY over a full-height content
  // area (matching the app's other frosted headers), so the technique review
  // video can ride up and pin over the entire header while the charts blur +
  // fade beneath it. The overlay's measured height is published as
  // `--insights-top` so each tab's scroll body clears it at rest.
  const bodyRef = useRef<HTMLDivElement>(null);
  // Callback ref (state, not useRef) so the measure runs when the header
  // actually mounts: in modal mode the Sheet body mounts later than this
  // component, so a useRef + useEffect([]) would fire before the header exists
  // and never re-run. See `useElementWidth` / the late-mount note.
  const [headerEl, setHeaderEl] = useState<HTMLDivElement | null>(null);
  useEffect(() => {
    const bodyEl = bodyRef.current;
    if (!bodyEl || !headerEl || typeof ResizeObserver === "undefined") return;
    const apply = () =>
      bodyEl.style.setProperty("--insights-top", `${headerEl.offsetHeight}px`);
    apply();
    const ro = new ResizeObserver(apply);
    ro.observe(headerEl);
    return () => ro.disconnect();
  }, [headerEl]);

  // Experimental mobile nav: the tab switcher moves to a solid bottom panel
  // (rep-selection pill styling, no icons), and the Technique tab's set/rep
  // selector portals into that panel above the tabs. Set/rep selection stays
  // owned by the Technique tab; other tabs show just the tab pills. Applies at
  // every size (modal + inline). Flip to false to restore the top underline tabs.
  const MOBILE_INSIGHTS_NAV = true;
  // Reversible (24.11.26): the bottom chip's tabs in the portal's
  // SegmentedPicker look (muted track, dark active pill). False restores the
  // red-orange tinted pills.
  const PORTAL_TAB_TRACK = true;
  const bottomNav = MOBILE_INSIGHTS_NAV;
  // Portal target for the active tab's controls (Technique's SetRepSelector).
  const [navSlot, setNavSlot] = useState<HTMLDivElement | null>(null);
  // Publish the bottom nav chip's height (+ room for its floating offset) as
  // `--insights-bottom` so each tab reserves space and its content scrolls UNDER
  // the floating chip, fading at the very bottom (mirrors `--insights-top`).
  const [footerEl, setFooterEl] = useState<HTMLDivElement | null>(null);
  useEffect(() => {
    const bodyEl = bodyRef.current;
    if (!bodyEl) return;
    if (!footerEl || typeof ResizeObserver === "undefined") {
      bodyEl.style.removeProperty("--insights-bottom");
      return;
    }
    const apply = () =>
      bodyEl.style.setProperty(
        "--insights-bottom",
        `${footerEl.offsetHeight + 40}px`,
      );
    apply();
    const ro = new ResizeObserver(apply);
    ro.observe(footerEl);
    return () => ro.disconnect();
  }, [footerEl]);

  const tabLabel = (id: InsightsTab) =>
    id === "overview"
      ? t("History")
      : id === "details"
        ? t("Details")
        : id === "performance"
          ? t("Performance")
          : id === "technique"
            ? t("Technique")
            : id === "live"
              ? isLive
                ? t({ text: "Live", context: "Insights tab: live session standings" })
                : t({ text: "Result", context: "Insights tab: the result of a live session that has ended" })
              : t("Reps");

  const scrollRegion = (
    <div className="relative flex min-h-0 flex-1 flex-col">
      <div className="flex min-h-0 flex-1 flex-col">
        {shownTab === "live" ? (
          isLive ? (
            <LiveTab session={session} />
          ) : (
            <LiveResultTab />
          )
        ) : shownTab === "details" ? (
          <DetailsTab
            session={session}
            header={detailsHeader}
            equipmentGroupID={equipmentGroupID}
            loadingCtx={loadingCtx}
            onSessionChange={onSessionChange}
          />
        ) : shownTab === "overview" ? (
          <OverviewTab
            session={session}
            exerciseGroupID={exerciseGroupID}
            equipmentGroupID={equipmentGroupID}
            loadingCtx={loadingCtx}
          />
        ) : shownTab === "technique" ? (
          <TechniqueTab
            loadIndependentOnly={feedback}
            session={session}
            exerciseGroupID={exerciseGroupID}
            exerciseBaseID={exerciseBaseID}
            isBarbell={isBarbell}
            onSelectedRepChange={setTechniqueRepId}
            navSlot={bottomNav ? navSlot : null}
          />
        ) : shownTab === "reps" ? (
          <RepsTab
            session={session}
            loadShare={repsLoadShare}
            exerciseGroupID={exerciseGroupID}
            onRepsChange={onRepsChange}
            deleteOnly={feedback}
            navSlot={bottomNav ? navSlot : null}
          />
        ) : (
          <PerformanceTab
            session={session}
            exerciseGroupID={exerciseGroupID}
            loadIndependentOnly={feedback}
          />
        )}
      </div>

      {/* One shell-level fade at the foot of the active tab's scroll body —
          every tab uses a flex-1 scroller that fills this `relative` region, so
          a single fade anchored here covers all of them. */}
      <ScrollEdgeFade />

      {/* Frosted overlay: Insights header (+ the underline tab switcher when the
          bottom nav is off). z-30 sits above the charts (which blur/fade under
          it) but below the review video (z-50). */}
      <div ref={setHeaderEl} className="absolute inset-x-0 top-0 z-30">
        <div className={`${headerEdgeClass(HEADER_BLUR)} relative isolate`}>
          <div
            className={`${HEADER_MIN_HEIGHT} flex items-center pb-4 pt-[calc(1rem+env(safe-area-inset-top))]`}
          >
            <ContentColumn className="flex min-w-0 items-center gap-4">
              {!inline && (
                <button
                  type="button"
                  onClick={onClose}
                  aria-label={t("Close")}
                  className={HEADER_ICON_BUTTON}
                >
                  <XIcon className="size-5" />
                </button>
              )}
              <h2 className="heading-large min-w-0 flex-1 truncate">
                {t("Insights")}
              </h2>
              {/* Flip trajectory only makes sense for the barbell bar-path data,
                  so the menu is hidden for non-barbell exercises. */}
              {tab === "technique" && isBarbell && onFlipRep && techniqueRepId && (
                // Zero-height slot, centred on the row: the 40 px button
                // would otherwise make this tab's title row taller than the
                // others' (where no button sits beside the title, as on the
                // iPad without a close button), pushing the title down.
                <div className="flex h-0 shrink-0 items-center">
                  <ActionMenu
                    ariaLabel={t("Technique actions")}
                    triggerClassName={HEADER_ICON_BUTTON}
                    items={[
                      {
                        label: t("Flip trajectory data"),
                        onClick: () => onFlipRep(techniqueRepId),
                      },
                    ]}
                  />
                </div>
              )}
            </ContentColumn>
          </div>

          {!bottomNav && (
            <ContentColumn className="-mt-3">
              {/* Negative inset matches the tab buttons' px-4 so the first tab
                  label lines up with the content column edge. */}
              <div className="-mx-4 flex shrink-0 gap-1">
                {TABS.map((id) => {
                  const active = id === tab;
                  return (
                    <button
                      key={id}
                      type="button"
                      onClick={() => setTab(id)}
                      aria-pressed={active}
                      className={`relative px-4 py-3 clickable-small transition-colors ${
                        active
                          ? "text-foreground-default"
                          : "text-foreground-muted hover:text-foreground-default"
                      }`}
                    >
                      {tabLabel(id)}
                      {active && (
                        <span className="absolute inset-x-3 bottom-0 h-[3px] rounded-full bg-foreground-red-orange" />
                      )}
                    </button>
                  );
                })}
              </div>
            </ContentColumn>
          )}
        </div>
      </div>
    </div>
  );

  const body = (
    <div ref={bodyRef} className="relative flex min-h-0 flex-1 flex-col">
      {scrollRegion}

      {/* Bottom nav (mobile): ONE floating chip whose background extends
          vertically over both rows — the active tab's controls (Technique's
          set/rep selector portals into `navSlot`, bare so it shares this chip)
          on top, the tab switcher (rep-selection pills) beneath. A flex child,
          so the scroll region above shrinks to clear it — no overlay padding. */}
      {bottomNav && (
        <div
          ref={setFooterEl}
          className="absolute inset-x-0 floating-bottom z-30 px-3 ios:px-2"
        >
          <ContentColumn className="flex justify-center">
            {/* `@container`: the portalled SetRepSelector caps its dropdown
                trigger/list with cq units, so they resolve against THIS chip's
                width (not the viewport) and stay contained in the chip. */}
            {/* Five tabs need more than four, and the live session's sixth
                more again: at the narrower width the last one was cut off
                wherever the pane had the room. */}
            <div
              className={`@container flex w-full ${
                TABS.length > 5
                  ? "max-w-xl"
                  : TABS.length > 4
                    ? "max-w-lg"
                    : "max-w-md"
              } flex-col gap-2 rounded-3xl bg-surface-base p-2 shadow-floating ring-1 ring-surface-stroke-muted`}
            >
              {/* Empty (and hidden) unless the active tab portals controls
                  here. Left-aligned: the set/rep selector reads from the
                  chip's left edge like a list row, not centered. */}
              <div
                ref={setNavSlot}
                className="flex min-w-0 justify-start px-1 empty:hidden"
              />
              {/* One row at every width. Where the chip is too narrow for
                  all labels (the tablet's split view with the sidebar open, a
                  phone with the fifth tab) the row scrolls sideways. Wrapping
                  them instead stacked up to three rows over the stat cards. */}
              {PORTAL_TAB_TRACK ? (
                // The portal's session-drawer tabs: the active tab as a dark
                // sliding pill. Scrolls sideways when the chip is too narrow
                // for every label.
                <div className="flex justify-center">
                  <SegmentedPicker
                    scrollable
                    // The chip is the surface: no muted track, only the
                    // active tab's dark pill.
                    track={false}
                    ariaLabel={t("Insights")}
                    value={shownTab}
                    onChange={setTab}
                    options={TABS.map((id) => ({ value: id, label: tabLabel(id) }))}
                  />
                </div>
              ) : (
                <TabPillRow activeKey={shownTab} count={TABS.length}>
                  {TABS.map((id) => {
                    const active = id === shownTab;
                    return (
                      <button
                        key={id}
                        type="button"
                        onClick={() => setTab(id)}
                        aria-pressed={active}
                        data-testid={`insights-tab-${id}`}
                        className={`clickable-small min-h-11 flex-1 whitespace-nowrap rounded-full border px-3 py-2 text-center transition-colors ${
                          active
                            ? "border-foreground-red-orange/30 bg-foreground-red-orange/10 text-foreground-default"
                            : "border-transparent text-foreground-muted hover:bg-surface-base-muted"
                        }`}
                      >
                        {tabLabel(id)}
                      </button>
                    );
                  })}
                </TabPillRow>
              )}
            </div>
          </ContentColumn>
        </div>
      )}
    </div>
  );

  // Inline mode (side-by-side with the tracking view): the pane is
  // always-mounted alongside its sibling, so no slide-in/out — just a
  // flex column owning its allotted width. `open` is ignored here; the
  // parent controls visibility by mounting/unmounting.
  if (inline) {
    return (
      <div
        role="region"
        aria-label={t("Insights")}
        className="flex h-full min-h-0 flex-col bg-background"
      >
        {body}
      </div>
    );
  }

  return (
    <Sheet
      open={open}
      onClose={onClose}
      slideFrom="bottom"
      ariaLabel={t("Insights")}
      zIndex={90}
      className="flex flex-col bg-background"
    >
      {body}
    </Sheet>
  );
}
