"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import type { ExerciseMappedReturnDto } from "@enode/core/api/dtos/exercises";
import { useExercisePresentation } from "@enode/core/exercises/presentation-hooks";
import { useMusclesVersion } from "@enode/core/muscles/hooks";
import { getMuscle, getMuscleByKey, loadMuscles } from "@enode/core/muscles/store";
import { getTextContent } from "@enode/core/text-content/store";
import { useTextContentsVersion } from "@enode/core/text-content/useTextContentsVersion";
import { weekEndExclusive, weekStartOf } from "@enode/core/training/calendar-week";
import type { WorkoutSession } from "@enode/core/training/models";
import {
  buildSessionMusclesVm,
  exerciseMuscles,
  solverMuscleMap,
} from "@enode/core/training/session-muscle-week";
import { useUserProfile, useWeekStats } from "@enode/core/users/hooks";
import { REP_BAR_THICKNESS_PX } from "@enode/ui/charts/metric-bar";
import { SessionTrainedSection } from "@enode/ui/session-details/session-trained-section";
import type { LiveSessionFacts } from "./session-details";

// Reversible: the session's part of the muscle bars (and its figures) in Deep
// Green, like the Your Week load bar — red-orange stays for highlights and
// outliers. `false` restores red-orange. The portal keeps red-orange either way.
const DEEP_GREEN_SESSION_BARS = true;

// Insights → Details → "What this session did", for the session being
// trained: the portal's section (`@enode/ui/session-details`), fed from the
// LIVE session instead of the server's session stats, which only exist once
// training finishes and the session is uploaded.
// - The muscles come from the exercise's solver category, the sets they got
//   from the performed work sets — the same weights the server counts with.
// - The week is the server's week for the athlete, which does not hold this
//   session yet, so its sets are added on top.
//
// TODO: the muscle-quality split (and a weightlifting session's lifts per
// band) is computed by the backend from the uploaded session; there is no
// client-side equivalent of its aggregation, so the live tab shows neither.
export function LiveSessionTrained({
  session,
  catalogueExercise,
  facts,
}: {
  session: WorkoutSession;
  /** The viewer's own exercise for the session's definition, if they have one. */
  catalogueExercise: ExerciseMappedReturnDto | undefined;
  facts: LiveSessionFacts;
}) {
  const { solverOrder } = useExercisePresentation(
    catalogueExercise,
    session.exerciseDefinitionID,
  );

  // The week the session is trained in — computed once: a training that runs
  // past midnight on Sunday stays in the week it started in.
  const [weekStart] = useState(() => weekStartOf(new Date(session.created)));
  const week = useWeekStats(session.userID, weekStart, weekEndExclusive(weekStart) - 1);
  // The athlete's own muscle rows: the week's rows may name muscles by them.
  const { profile } = useUserProfile(session.userID);
  const [currentWeekStart] = useState(() => weekStartOf());

  // Muscle names and keys come from the catalogues; their versions re-derive
  // the rows once they land.
  useEffect(() => {
    void loadMuscles().catch(() => {});
  }, []);
  const musclesVersion = useMusclesVersion();
  const textsVersion = useTextContentsVersion();
  const athleteMuscles = profile?.muscles ?? null;
  const muscleKeyOf = useCallback(
    (muscleId: string) =>
      getMuscle(muscleId)?.key ??
      athleteMuscles?.find((muscle) => muscle.id === muscleId)?.key ??
      null,
    // eslint-disable-next-line react-hooks/exhaustive-deps -- the catalogue version stands in for getMuscle
    [athleteMuscles, musclesVersion],
  );
  const muscleMap = useMemo(
    () =>
      solverMuscleMap(solverOrder, (key) =>
        getTextContent(getMuscleByKey(key)?.nameTextContentID),
      ),
    // eslint-disable-next-line react-hooks/exhaustive-deps -- the catalogue versions stand in for the store reads
    [solverOrder, musclesVersion, textsVersion],
  );

  const weekUsage = week.status === "loaded" ? week.stats?.muscleUsage : null;
  const muscles = useMemo(
    () =>
      buildSessionMusclesVm({
        muscleMapVolume: muscleMap,
        solverOrder,
        workSets: facts.workSetRows,
        weekUsage,
        muscleKeyOf,
        weekIncludesSession: false,
      }),
    [muscleMap, solverOrder, facts.workSetRows, weekUsage, muscleKeyOf],
  );

  // Warm-ups only: no work set counts toward the week — the card shows what
  // the exercise trains instead.
  const warmupsOnly = facts.workingSets === 0 && facts.warmupSets > 0;
  const exercise = useMemo(
    () => (warmupsOnly ? exerciseMuscles({ muscleMapVolume: muscleMap, solverOrder }) : null),
    [warmupsOnly, muscleMap, solverOrder],
  );

  return (
    <SessionTrainedSection
      muscles={muscles}
      week={{
        start: weekStart,
        isCurrentWeek: weekStart === currentWeekStart,
        status: week.status,
        state: week.state,
        retry: week.retry,
      }}
      zoneDistribution={null}
      goalSplit={null}
      lifts={null}
      warmupsOnly={warmupsOnly}
      exercise={exercise}
      sessionTone={DEEP_GREEN_SESSION_BARS ? "deepGreen" : "redOrange"}
      // The app's one bar thickness, as pills like its other value bars.
      barThicknessPx={REP_BAR_THICKNESS_PX}
      // The title as the card's heading, like the other Details cards.
      titleInCard
      // A narrow card keeps the table, with muscle icons for the names.
      narrowIcons
    />
  );
}
