"use client";

import { useState } from "react";

import type { MetricReturnDto } from "@enode/core/api/dtos/metrics";
import type { WorkoutRep, WorkoutSet } from "@enode/core/training/models";
import { findMeasurementDisplayValue } from "@enode/core/training/measurements";
import { compareRepsByCreated } from "@enode/core/training/rep-order";
import { countedRepCount } from "@enode/core/training/rep-scope";
import { useTranslation } from "@enode/core/translations/hooks";
import { RepPairList, type RepBarScales } from "@enode/ui/reps/rep-pair-list";
import { RepSelectActions } from "@enode/ui/reps/rep-select-actions";
import { useRepTagging } from "@enode/ui/reps/use-rep-tagging";

import { ChevronDownIcon, ChevronUpIcon } from "./icons";

// Collapsible per-rep card. Summary line shows the tracked count and
// (when any rep is flagged invalid) the invalid count. Expanded body
// lists every rep — tap-to-select toggles the rep into a multi-select;
// the floating action pill below the card surfaces Tag / Toggle valid /
// Delete / Done.
//
// Open by default: users asked support where the single reps are, with the
// card closed in front of them.
export function RepsCard({
  set,
  focusMetrics,
  onRepsChange,
}: {
  set: WorkoutSet;
  focusMetrics: MetricReturnDto[];
  onRepsChange: (reps: WorkoutRep[]) => void;
}) {
  const { t } = useTranslation();
  const [expanded, setExpanded] = useState(true);
  const [selectedIDs, setSelectedIDs] = useState<Set<string>>(new Set());

  // Snap selection back to the empty set whenever the underlying set
  // changes (the parent reseats the editor on a new set), so a stale
  // id list doesn't leak across edits.
  const [prevSetId, setPrevSetId] = useState(set.id);
  if (prevSetId !== set.id) {
    setPrevSetId(set.id);
    setSelectedIDs(new Set());
    setExpanded(true);
  }

  // Only for the summary counts below — the list itself sorts and pairs the
  // reps in `RepPairList`.
  const reps = [...set.reps].sort(compareRepsByCreated);
  // Tracked-rep count follows the shared `isCounted` rule (valid concentrics)
  // so it always equals the set's repCount measurement — toggling a rep
  // invalid drops the headline immediately. The invalid count next to it stays
  // across BOTH phases, so the coach still sees everything flagged.
  const summary = t(
    "{count, plural, one {# Tracked rep} other {# Tracked reps}}",
    { count: countedRepCount(reps) },
  );
  const invalidCount = reps.filter((r) => !r.valid).length;

  // Quick read (25.11.26): the first two focus metrics only, each with a bar
  // under its value scaled to the set's largest reading.
  const shownMetrics = focusMetrics.slice(0, 2);
  const scales: RepBarScales = new Map(
    shownMetrics.flatMap((metric) => {
      const id = metric.id;
      if (!id) return [];
      const values = reps
        .map((rep) => findMeasurementDisplayValue(rep.measurements, id, set))
        .filter((v): v is number => v != null && Number.isFinite(v));
      const max = Math.max(0, ...values);
      return max > 0 ? [[id, max] as const] : [];
    }),
  );

  function toggleSelected(id: string): void {
    setSelectedIDs((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  }

  function clearSelection(): void {
    setSelectedIDs(new Set());
  }

  // Flip `valid` on every selected rep — each rep toggles independently,
  // so a mixed selection ends up still mixed but inverted. Selection
  // stays so the user can chain further actions.
  function handleToggleValid(): void {
    onRepsChange(
      set.reps.map((r) =>
        selectedIDs.has(r.id) ? { ...r, valid: !r.valid } : r,
      ),
    );
  }

  function handleDeleteSelected(): void {
    onRepsChange(set.reps.filter((r) => !selectedIDs.has(r.id)));
    clearSelection();
  }

  // Tag the selected reps; the selection stays, like Toggle valid.
  const tagging = useRepTagging({
    selected: set.reps.filter((r) => selectedIDs.has(r.id)),
    contextTagIDs: set.reps.flatMap((r) => r.assignedTagIDs),
    onChange: (next) =>
      onRepsChange(
        set.reps.map((r) => {
          const ids = next.get(r.id);
          return ids ? { ...r, assignedTagIDs: ids } : r;
        }),
      ),
  });

  return (
    <>
      <div className="overflow-hidden rounded-2xl border border-surface-stroke bg-surface-base">
        <button
          type="button"
          onClick={() => setExpanded((v) => !v)}
          aria-expanded={expanded}
          className="flex w-full items-center gap-3 px-4 py-3 text-left hover:bg-surface-base-muted"
        >
          <span className="body-prominent">{summary}</span>
          <span className="flex-1" />
          {invalidCount > 0 && (
            <span className="stat-small uppercase text-feedback-error">
              {t("{count} invalid", { count: invalidCount })}
            </span>
          )}
          {expanded ? (
            <ChevronUpIcon className="size-4 text-foreground-muted" />
          ) : (
            <ChevronDownIcon className="size-4 text-foreground-muted" />
          )}
        </button>
        {expanded && (
          <>
            <div className="border-t border-surface-stroke" />
            {/* One scroll container for every row. The compact list fits the
                card's width, so it only scrolls vertically. */}
            <div className="max-h-72 overflow-auto">
              <RepPairList
                set={set}
                metrics={shownMetrics}
                scales={scales}
                compact
                // No set-average row over the reps (24.11.26): the edit view
                // is about the single reps; the set's average is on its row.
                showHeadings
                selectedIDs={selectedIDs}
                onToggleRep={toggleSelected}
                showTags
              />
            </div>
          </>
        )}
      </div>
      {selectedIDs.size > 0 && (
        <div className="flex justify-center pt-1">
          <RepSelectActions
            onTag={tagging.toggleOpen}
            tagButtonRef={tagging.triggerRef}
            onToggleValid={handleToggleValid}
            onDelete={handleDeleteSelected}
            onDone={clearSelection}
          />
        </div>
      )}
      {tagging.overlay}
    </>
  );
}
