"use client";

import type { UserReducedReturnDto } from "@enode/core/api/dtos/users";
import type { WorkoutReturnDtoV2 } from "@enode/core/api/dtos/workouts";
import { useTranslation } from "@enode/core/translations/hooks";
import { Button } from "@enode/ui/button";
import { ContentColumn } from "@enode/ui/content-column";
import { ScrollEdgeFade } from "@enode/ui/scroll-edge-fade";
import { WorkoutsTodayList } from "./workouts-today-list";
import { CreateWorkoutFab } from "./create-workout-fab";
import { RequestStationSlotOverlay } from "./request-station-slot-overlay";
import { ParticipantChip } from "./wellness/participant-chip";

// The today's-workouts content: the scrollable list and the floating "+" start
// menu. Extracted from the page's single-station branch so the SAME pane backs
// both the phone full-viewport view and an empty pad station column (a station
// with no active workout shows this inside its space). The "make offline-ready"
// action now lives in the station sidebar (the "Load workouts" row), so it's no
// longer shown here.
//
// Positioning is caller-owned: `topPadClass` clears whatever header sits above
// the scroller, and `fabClassName` floats the FAB over the viewport (phone:
// `fixed`) or anchors it inside a column (`absolute`).
export function TodayWorkoutsPane({
  loading,
  workouts,
  onSelectWorkout,
  onRefresh,
  onCreateNew,
  onOpenLibrary,
  onFeedbackTraining,
  onLogPastWorkout,
  checkIn,
  topPadClass,
  fabClassName,
  showFab = true,
  recordingLocked = false,
  onRequestSlot,
  requestingSlot = false,
}: {
  loading: boolean;
  workouts: WorkoutReturnDtoV2[] | null;
  onSelectWorkout: (w: WorkoutReturnDtoV2) => void;
  onRefresh: () => void;
  onCreateNew: () => void;
  // Opens the template Library — the FAB menu's only template entry.
  onOpenLibrary: () => void;
  onFeedbackTraining: () => void;
  // Optional retrospective-input entry. When provided, a prominent card at the
  // top of the list opens the "log a past workout" flow (gated by the host).
  onLogPastWorkout?: () => void;
  // Optional wellness-check-in entry, in the same card shape. The host decides
  // whether it applies today (see `useCheckedInToday`) — this only renders it.
  // One object rather than six props: it travels through the station column to
  // get here, and drilling them separately would bury the column's own API.
  checkIn?: CheckInCardConfig;
  topPadClass: string;
  fabClassName: string;
  showFab?: boolean;
  // When the device's session weight won't allow recording another workout,
  // block the real-start paths (workout selection + the create/template FAB)
  // and surface the request-slot overlay. Feedback training stays available.
  recordingLocked?: boolean;
  onRequestSlot?: () => void;
  requestingSlot?: boolean;
}) {
  const { t } = useTranslation();
  return (
    <div className="relative flex min-h-0 flex-1 flex-col">
      <div
        // 6rem (96px): extra room below the last card so it can scroll clear
        // of the bottom ScrollEdgeFade (h-16 / 64px) instead of resting under
        // it; + the safe-area inset so the room survives Android edge-to-edge.
        className={`scrollbar-none min-h-0 flex-1 overflow-y-auto pb-[calc(6rem+env(safe-area-inset-bottom))] ${topPadClass}`}
      >
        <ContentColumn className="space-y-6">
          {/* The daily check-in sits above the retrospective entrance: it is
              the thing to do BEFORE training, so it reads first. Unlike that
              card it stays available while recording is locked — answering five
              questions doesn't need a station slot. */}
          {checkIn && <WellnessCheckInCard {...checkIn} />}
          {/* Prominent "log a past workout" entrance — first element under the
              header, above today's list. */}
          {onLogPastWorkout && !recordingLocked && (
            <LogPastWorkoutCard onClick={onLogPastWorkout} />
          )}
          {loading && (
            <p className="body-normal text-foreground-muted">{t("Loading…")}</p>
          )}
          {!loading && workouts && (
            <WorkoutsTodayList
              workouts={workouts}
              onSelect={onSelectWorkout}
              emptyAction={{ label: t("Try again"), onClick: onRefresh }}
            />
          )}
        </ContentColumn>
      </div>

      {/* Soft fade at the foot of the scroll area — scroll affordance, matching
          active tracking / training. Sibling of the scroller, anchored to this
          positioned pane so it never repaints on scroll. */}
      <ScrollEdgeFade />

      {/* The real-start FAB is hidden while locked — the overlay below carries
          the only two allowed actions (request a slot / feedback training). */}
      {showFab && !recordingLocked && (
        <CreateWorkoutFab
          className={fabClassName}
          onCreateNew={onCreateNew}
          onOpenLibrary={onOpenLibrary}
          onFeedbackTraining={onFeedbackTraining}
        />
      )}

      {recordingLocked && onRequestSlot && (
        <RequestStationSlotOverlay
          title={t("No station slot available")}
          message={t(
            "This device can't record another workout right now. Request a station slot, or run feedback training — feedback isn't recorded.",
          )}
          onRequest={onRequestSlot}
          requesting={requestingSlot}
          secondaryLabel={t("Feedback training")}
          onSecondary={onFeedbackTraining}
        />
      )}
    </div>
  );
}

// The third way into the wellness check-in, alongside the pre-workout gate and
// the daily reminder — for an athlete who wants to answer it without starting a
// training. Deliberately the same shape as the card below rather than a new
// treatment: two entrances competing for the same spot should read as siblings.
//
// It carries ONLY a coach's ATHLETES. Someone with no email never sees a prompt
// of their own, so unless a coach answers for them their wellness data simply
// doesn't exist — and the only other place to do that is inside a running
// training. The signed-in user's own check-in used to sit here too and now lives
// in the notifications drawer's pinned prompt (docs/notifications.md), so the
// same offer isn't made twice on one screen.
export type CheckInCardConfig = {
  /** Those known to still owe a check-in today. Empty hides the card. */
  athletes: readonly UserReducedReturnDto[];
  checkInEnabled: boolean;
  onCheckInAthlete: (athlete: UserReducedReturnDto) => void;
};

function WellnessCheckInCard({
  athletes,
  checkInEnabled,
  onCheckInAthlete,
}: CheckInCardConfig) {
  const { t } = useTranslation();
  return (
    <section className="rounded-2xl border border-surface-stroke bg-surface-base p-4">
      <h3 className="heading-normal">{t("Daily check-in")}</h3>
      {/* Gated on the list itself: it holds exactly those known to still owe a
          check-in, and once it empties there is nothing left to offer. The card
          as a whole is hidden at that point too (see `showCheckInCard`). */}
      {athletes.length > 0 && (
        <div className="mt-1">
          <p className="body-small text-foreground-muted">
            {t("Athletes without their own login — answer for them here.")}
          </p>
          {/* The SAME component the training view's athlete row uses, so the
              badge, the per-athlete lookup and its dedupe are one implementation
              rather than two that can drift. Only these rendered chips hit the
              network — a roster of hundreds must not fan out on the dashboard. */}
          <div className="scrollbar-none mt-3 flex gap-3 overflow-x-auto empty:mt-0">
            {athletes.map((athlete) => (
              <ParticipantChip
                key={athlete.id}
                participant={athlete}
                enabled={checkInEnabled}
                onCheckIn={onCheckInAthlete}
              />
            ))}
          </div>
        </div>
      )}
    </section>
  );
}

// Prominent entrance for logging a workout that wasn't tracked live — a titled
// card with a short explanation and a CTA that opens the retrospective flow.
function LogPastWorkoutCard({ onClick }: { onClick: () => void }) {
  const { t } = useTranslation();
  return (
    <section className="rounded-2xl border border-surface-stroke bg-surface-base p-4">
      <h3 className="heading-normal">{t("Log a past workout")}</h3>
      <p className="body-small mt-1 text-foreground-muted">
        {t(
          "Trained without the app? Enter the sets you completed and upload them to your history.",
        )}
      </p>
      <Button
        variant="primary"
        size="rounded"
        className="mt-3"
        onClick={onClick}
      >
        {t("Log past workout")}
      </Button>
    </section>
  );
}
