"use client";

import { LOOK } from "@enode/ui/live/look";
import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import type {
  HistoryStatsReturnDtoV2,
  LiftsSummaryReturnDto,
  MuscleUsageReturnDtoV2,
  ZoneReturnDto,
} from "@enode/core/api/dtos/history-stats";
import type { SessionReturnDto } from "@enode/core/api/dtos/sessions";
import type { TrainingGoalReturnDto } from "@enode/core/api/dtos/training-goals";
import type { EntityTagReturnDto } from "@enode/core/api/dtos/tags";
import { deleteSession } from "@enode/core/api/sessions";
import {
  liftBandFigures,
  sessionLiftSets,
} from "@enode/core/analysis/lift-bands";
import {
  countWarmupSets,
  countWorkingSets,
  summarizeSession,
} from "@enode/core/training/exercise-overview";
import { countSessionReps } from "@enode/core/training/session-facts";
import { useMusclesVersion } from "@enode/core/muscles/hooks";
import { getMuscle, loadMuscles } from "@enode/core/muscles/store";
import { useUserProfile, useWeekStats } from "@enode/core/users/hooks";
import { loadWeekStats } from "@enode/core/users/week-stats-store";
import { useTranslation } from "@enode/core/translations/hooks";
import { ConfirmDialog } from "@enode/ui/confirm-dialog";
import { toast } from "@enode/ui/feedback/toast-store";
import { presentError } from "@enode/ui/feedback/use-error-presenter";
import { ChartIcon, TrashIcon } from "@enode/ui/icons";
import { SessionDetailsCard } from "@enode/ui/session-details/session-details-card";
import { SessionFactsGrid } from "@enode/ui/session-details/session-facts-grid";
import { SessionNoteCard } from "@enode/ui/session-details/session-note-card";
import { REP_BAR_THICKNESS_PX } from "@enode/ui/charts/metric-bar";
import { InlineTagsEditor } from "../../components/inline-tags-editor";
import { goalSplit } from "./muscle-goals-view-model";
import {
  buildSessionMusclesVm,
  exerciseMuscles,
  sessionWorkSetCount,
} from "@enode/core/training/session-muscle-week";
import {
  SessionTrainedSection,
  SessionTrainedSectionSkeleton,
  type SessionWeekFigures,
} from "@enode/ui/session-details/session-trained-section";
import { weekEndExclusive, weekStartOf } from "./users/drawer-week";
import { useSessionMetrics } from "./use-session-metrics";

// Session drawer → Details tab: everything about the ONE session, and what can
// be changed on it — who and what it was (with the athlete / exercise swaps),
// what it trained (the sets it added to each muscle's week + qualities or
// lifts, from the session's history stats and its week's stats), its tags and
// note, and the session-level actions (inspect
// profile, delete). The History tab next to it compares the session with
// earlier ones; nothing here looks across sessions. The tracking app's Details
// tab shares the facts, note and titled-card blocks (`@enode/ui/session-details`).
//
// One reading order, top to bottom — no side column competing for the eye:
// - who and what (one row of fact cells: athlete and exercise with their
//   "Change", the date, sets and reps or lifts);
// - what the session did — the muscles card (body map beside the main work and
//   every muscle's week), then the session's character (muscle qualities
//   against the goal, or lifts per band) beside the coach's own additions:
//   the tags over a short note, in one compact card;
// - the session actions as a quiet footer.
// Layout follows the DRAWER width (it is resizable), via `@container`; each
// block lays out by its own width (see each).

/** Session-level actions the host can offer; each one shows only when passed. */
export type SessionDetailsActions = {
  onChangeAthlete?: () => void;
  onChangeExercise?: () => void;
  onInspectProfile?: () => void;
  /** After the session was deleted — the host closes the drawer and refreshes. */
  onDeleted?: () => void;
};

export function SessionDetailsTab({
  session,
  exerciseName,
  exerciseDetail,
  historyStats,
  historyStatsLoading,
  tags,
  note,
  actions,
}: {
  /** The session with its full set tree once loaded (the counts read it). */
  session: SessionReturnDto;
  exerciseName: string;
  exerciseDetail: string | null;
  historyStats: HistoryStatsReturnDtoV2 | null;
  historyStatsLoading: boolean;
  tags: {
    tags: ReadonlyArray<EntityTagReturnDto>;
    /** Identity of the data `tags` came from — see InlineTagsEditor. */
    source: object;
    canEdit: boolean;
    onCommit: (
      next: EntityTagReturnDto[],
      previous: ReadonlyArray<EntityTagReturnDto>,
    ) => Promise<void>;
  };
  note: {
    note: string | null;
    /** Omit for a read-only note. */
    onSave?: (next: string) => Promise<void>;
  };
  actions: SessionDetailsActions & { canDelete: boolean };
}) {
  const { t } = useTranslation();
  const sets = session.sets ?? [];
  // A weightlifting session counts lifts, not concentric reps — known once the
  // session's history stats have loaded.
  const lifts = liftBandFigures(historyStats?.liftsSummary)?.lifts ?? null;

  return (
    <div className="@container mx-auto flex w-full max-w-[110rem] flex-col gap-6">
      <SessionFactsGrid
        athleteName={session.user?.name ?? null}
        athleteID={session.user?.id ?? null}
        exerciseName={exerciseName}
        exerciseDetail={exerciseDetail}
        startedAt={session.created ?? null}
        workingSets={countWorkingSets(sets)}
        warmupSets={countWarmupSets(sets)}
        reps={countSessionReps(sets)}
        lifts={lifts}
        onChangeAthlete={actions.onChangeAthlete}
        onChangeExercise={actions.onChangeExercise}
      />
      <TrainedSection
        session={session}
        historyStats={historyStats}
        historyStatsLoading={historyStatsLoading}
        beside={
          // The coach's own additions in one compact card: the tags over a
          // short note.
          <section className={`min-w-0 ${LOOK.panel} p-5`}>
            <SessionDetailsCard title={t("Tags")} bare>
            <InlineTagsEditor
              entityKind="session"
              tags={tags.tags}
              source={tags.source}
              canEdit={tags.canEdit}
              // Room for every tag: this is the session's own tag list,
              // not a table cell.
              max={50}
              onCommit={tags.onCommit}
              />
            </SessionDetailsCard>
            <div className="mt-4 border-t border-surface-stroke-muted pt-4">
              <SessionNoteCard note={note.note} onSave={note.onSave} bare rows={3} />
            </div>
          </section>
        }
      />
      <SessionActions sessionID={session.id} actions={actions} />
    </div>
  );
}

// What the session trained: the sets it added to each muscle's week, and the
// muscle-quality split (strength sessions) or the lifts per band
// (weightlifting) — from the session's history stats, plus the stats of the
// session's week for the week figures.
function TrainedSection({
  session,
  historyStats,
  historyStatsLoading,
  beside,
}: {
  session: SessionReturnDto;
  historyStats: HistoryStatsReturnDtoV2 | null;
  historyStatsLoading: boolean;
  /** Rendered beside the session's character card (the tags and note). */
  beside: ReactNode;
}) {
  const { resolve } = useSessionMetrics();
  const { ids, focusKey, isStrength } = resolve(session);
  // The week figures need the athlete and the session's date. Without either
  // (never expected for a stored session) the rows show the session's sets
  // only — and no week is fetched: a null athlete would load the VIEWER's week.
  const athleteID = session.user?.id ?? null;
  const weekStart =
    typeof session.created === "number"
      ? weekStartOf(new Date(session.created))
      : null;
  // Started next to the session's stats rather than after them; the section
  // below reads the same cache entry.
  useEffect(() => {
    if (athleteID && weekStart != null) {
      loadWeekStats(athleteID, weekStart, weekEndExclusive(weekStart) - 1);
    }
  }, [athleteID, weekStart]);

  // A weightlifting session has no zone distribution (the key is absent): no
  // quality split then.
  const showZones =
    isStrength &&
    (historyStatsLoading || historyStats?.zoneDistribution != null);
  // 17.11.26 (W-1) — a weightlifting session's lifts per band take the split's
  // place, from the session route's `liftsSummary`; without lifts there are
  // none. While loading, a lift session keeps the slot's skeleton.
  const showLifts = historyStatsLoading
    ? focusKey === "loadingMass"
    : liftBandFigures(historyStats?.liftsSummary) != null;

  if (historyStatsLoading) {
    return (
      <SessionTrainedSectionSkeleton
        withMix={showZones || showLifts}
        beside={beside}
        titleInCard
      />
    );
  }

  // 17.11.26 (test round 6, r6-7) — the sets behind the lifts, for "12 sets ·
  // 20 lifts". Server first (backend response 8): the summary's `sets`; from
  // older servers the completed work sets at ≥ 50 % of the session's PB.
  const liftSets = showLifts
    ? sessionLiftSets(
        historyStats?.liftsSummary,
        () => summarizeSession(session, ids, { completedOnly: true }).setRows,
      )
    : null;
  const mix: TrainedMix = {
    zoneDistribution: showZones
      ? (historyStats?.zoneDistribution ?? null)
      : null,
    lifts: showLifts
      ? { summary: historyStats?.liftsSummary, sets: liftSets }
      : null,
  };

  if (athleteID && weekStart != null) {
    return (
      <TrainedSectionWithWeek
        session={session}
        historyStats={historyStats}
        mix={mix}
        beside={beside}
        athleteID={athleteID}
        weekStart={weekStart}
      />
    );
  }
  return (
    <TrainedSectionBody
      session={session}
      historyStats={historyStats}
      mix={mix}
      beside={beside}
      week={null}
      weekUsage={null}
      goal={null}
      athleteMuscles={null}
    />
  );
}

type TrainedMix = {
  zoneDistribution: ZoneReturnDto | null;
  lifts: {
    summary: LiftsSummaryReturnDto | null | undefined;
    sets: number | null;
  } | null;
};

// Loads the session's week — the same `POST /history/v2/week` (and cache entry)
// the athlete drawer reads for that week — and the athlete's profile, for the
// training goal's split and the athlete's own muscle rows.
function TrainedSectionWithWeek({
  session,
  historyStats,
  mix,
  beside,
  athleteID,
  weekStart,
}: {
  session: SessionReturnDto;
  historyStats: HistoryStatsReturnDtoV2 | null;
  mix: TrainedMix;
  beside: ReactNode;
  athleteID: string;
  weekStart: number;
}) {
  const weekStats = useWeekStats(
    athleteID,
    weekStart,
    weekEndExclusive(weekStart) - 1,
  );
  const { profile } = useUserProfile(athleteID);
  // Computed once per mount, like the athlete drawer's current week.
  const [currentWeekStart] = useState(() => weekStartOf());
  return (
    <TrainedSectionBody
      session={session}
      historyStats={historyStats}
      mix={mix}
      beside={beside}
      week={{
        start: weekStart,
        isCurrentWeek: weekStart === currentWeekStart,
        status: weekStats.status,
        state: weekStats.state,
        retry: weekStats.retry,
      }}
      weekUsage={
        weekStats.status === "loaded" ? weekStats.stats?.muscleUsage : null
      }
      goal={profile?.trainingGoal ?? null}
      athleteMuscles={profile?.muscles ?? null}
    />
  );
}

function TrainedSectionBody({
  session,
  historyStats,
  mix,
  beside,
  week,
  weekUsage,
  goal,
  athleteMuscles,
}: {
  session: SessionReturnDto;
  historyStats: HistoryStatsReturnDtoV2 | null;
  mix: TrainedMix;
  beside: ReactNode;
  week: SessionWeekFigures | null;
  weekUsage: MuscleUsageReturnDtoV2 | null | undefined;
  goal: TrainingGoalReturnDto | null;
  athleteMuscles: readonly { id: string; key?: string | null }[] | null;
}) {
  // The week's rows name muscles by id — the catalogue's or the athlete's
  // own — so both are tried for the map key. The catalogue may land after the
  // stats; its version re-derives the rows then.
  useEffect(() => {
    void loadMuscles().catch(() => {});
  }, []);
  const musclesVersion = useMusclesVersion();
  const muscleKeyOf = useCallback(
    (muscleId: string) =>
      getMuscle(muscleId)?.key ??
      athleteMuscles?.find((m) => m.id === muscleId)?.key ??
      null,
    // eslint-disable-next-line react-hooks/exhaustive-deps -- the catalogue version stands in for getMuscle
    [athleteMuscles, musclesVersion],
  );
  const solverOrder = session.exercise?.exerciseSolverCategory?.order ?? null;
  const muscles = useMemo(
    () =>
      buildSessionMusclesVm({
        muscleMapVolume: historyStats?.muscleMapVolume,
        solverOrder,
        workSets: sessionWorkSetCount(historyStats?.gridMetrics),
        weekUsage,
        muscleKeyOf,
      }),
    [historyStats, solverOrder, weekUsage, muscleKeyOf],
  );
  const split = useMemo(() => goalSplit(goal), [goal]);
  // Warm-ups only: the backend counts no work set, so the session's own
  // figures are all zero — the card shows what the exercise trains instead.
  const sets = session.sets ?? [];
  const warmupsOnly = countWorkingSets(sets) === 0 && countWarmupSets(sets) > 0;
  const exercise = useMemo(
    () =>
      warmupsOnly
        ? exerciseMuscles({ muscleMapVolume: historyStats?.muscleMapVolume, solverOrder })
        : null,
    [warmupsOnly, historyStats, solverOrder],
  );

  return (
    <SessionTrainedSection
      muscles={muscles}
      week={week}
      zoneDistribution={mix.zoneDistribution}
      goalSplit={mix.zoneDistribution ? split : null}
      lifts={mix.lifts}
      beside={beside}
      warmupsOnly={warmupsOnly}
      exercise={exercise}
      // The tracking app's look: the session's part in Deep Green (red-orange
      // marks highlights and warnings, not volume), pill bars at the shared
      // bar thickness, and the title as the card's own heading. Muscle names
      // stay on narrow cards (no `narrowIcons`).
      sessionTone="deepGreen"
      barThicknessPx={REP_BAR_THICKNESS_PX}
      titleInCard
    />
  );
}

// Inspect profile and delete, as two quiet text actions under the cards — no
// divider, no filled buttons: actions on the session, not content about it,
// so they don't compete with it. Delete asks first.
const QUIET_ACTION =
  "clickable-small inline-flex items-center gap-2 rounded-full px-3 py-2 transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-foreground-red-orange";

function SessionActions({
  sessionID,
  actions,
}: {
  sessionID: string;
  actions: SessionDetailsActions & { canDelete: boolean };
}) {
  const { t } = useTranslation();
  const [confirmOpen, setConfirmOpen] = useState(false);
  const [deleting, setDeleting] = useState(false);

  async function confirmDelete() {
    setDeleting(true);
    try {
      await deleteSession(sessionID);
      toast.success(t("Session deleted"));
      setConfirmOpen(false);
      actions.onDeleted?.();
    } catch (err) {
      setConfirmOpen(false);
      presentError(err, t, { onRetry: confirmDelete });
    } finally {
      setDeleting(false);
    }
  }

  const canDelete = actions.canDelete && actions.onDeleted != null;
  if (!actions.onInspectProfile && !canDelete) return null;

  return (
    <div>
      {/* `-ml-3`: the first action's text lines up with the cards' edge. */}
      <div className="-ml-3 flex flex-wrap items-center gap-1">
        {actions.onInspectProfile && (
          <button
            type="button"
            onClick={actions.onInspectProfile}
            className={`${QUIET_ACTION} text-foreground-default hover:bg-surface-base-muted`}
          >
            <ChartIcon className="size-4 text-foreground-muted" />
            {t("Inspect Profile")}
          </button>
        )}
        {canDelete && (
          <button
            type="button"
            onClick={() => setConfirmOpen(true)}
            className={`${QUIET_ACTION} text-feedback-error hover:bg-feedback-error-surface`}
          >
            <TrashIcon className="size-4" />
            {t("Delete session")}
          </button>
        )}
      </div>
      <ConfirmDialog
        open={confirmOpen}
        destructive
        title={t("Delete session?")}
        message={t(
          "This permanently deletes the session and all its sets, reps and videos. This can’t be undone.",
        )}
        confirmLabel={t("Delete")}
        busy={deleting}
        onConfirm={() => void confirmDelete()}
        onCancel={() => setConfirmOpen(false)}
      />
    </div>
  );
}
