"use client";

import type { ReactNode } from "react";
import type { UserReducedReturnDto } from "@enode/core/api/dtos/users";
import type { WorkoutReturnDtoV2 } from "@enode/core/api/dtos/workouts";
import { useIsAthlete } from "@enode/core/current-user/hooks";
import { useTranslation } from "@enode/core/translations/hooks";
import { Button } from "@enode/ui/button";
import { ContentColumn } from "@enode/ui/content-column";
import { ChevronRightIcon } from "@enode/ui/icons";
import { ScrollEdgeFade } from "@enode/ui/scroll-edge-fade";
import { WorkoutsTodayList } from "./workouts-today-list";
import { CreateWorkoutFab } from "./create-workout-fab";
import { DeviceVideosCard } from "./device-videos/device-videos-card";
import { AthletesCheckInRow } from "./wellness/athletes-check-in-row";
import { NoTrainingStationCard } from "./no-training-station-card";
import { columnStartPaths } from "./tablet-rail-model";

// 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,
  scheduleUnavailable = false,
  onSelectWorkout,
  onRefresh,
  onCreateNew,
  onOpenLibrary,
  onFeedbackTraining,
  onLogPastWorkout,
  checkIn,
  lead,
  topPadClass,
  fabClassName,
  showFab = true,
  recordingLocked = false,
  feedbackOnly = false,
  offerStation = false,
}: {
  loading: boolean;
  workouts: WorkoutReturnDtoV2[] | null;
  // The schedule could not be loaded and nothing stored stood in. Changes what
  // the empty list says — "nothing scheduled" would be a guess.
  scheduleUnavailable?: boolean;
  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;
  // What belongs to the signed-in person rather than to the schedule — their
  // own week, their live session. Leads the pane, above everything a coach
  // does for others. The host builds it; null shows nothing.
  lead?: ReactNode;
  topPadClass: string;
  fabClassName: string;
  showFab?: boolean;
  // The server refused this device a station (`useTodayStation().locked`):
  // hide the real-start paths (log past workout + the FAB). Today stays
  // readable — nothing covers it; the card keeps Feedback training.
  recordingLocked?: boolean;
  // A feedback station: this column cannot save (beyond the device's
  // training stations). It shows no schedule and nothing that saves — the
  // feedback-station card offers Feedback training instead.
  feedbackOnly?: boolean;
  // The left-most feedback station: its card also offers a training station.
  offerStation?: boolean;
}) {
  const { t } = useTranslation();
  // An athlete's pane is one person's own day: their week, then today's
  // workout. Logging a past workout is the exception, so for them it follows
  // the schedule as a quiet row instead of standing above it as the loudest
  // thing on the screen. A coach's pane keeps its order — there the card is a
  // frequent job (athletes who trained without the tablet).
  const ownDay = useIsAthlete();
  const paths = columnStartPaths({ feedbackOnly, recordingLocked });
  // Nothing that saves can start here (a feedback station, or a locked
  // device): the card replaces the schedule.
  const feedbackStation = !paths.workouts;
  // Two rows of one kind — the athletes' check-ins and the coach's own — so
  // they sit closer together than the cards around them.
  const checkInRows =
    !ownDay && (checkIn || lead) ? (
      <div className="space-y-2">
        {checkIn && (
          <AthletesCheckInRow
            athletes={checkIn.athletes}
            onCheckInAthlete={checkIn.onCheckInAthlete}
          />
        )}
        {lead}
      </div>
    ) : null;
  const logPast =
    onLogPastWorkout && paths.logPast ? (
      <LogPastWorkoutCard onClick={onLogPastWorkout} quiet={ownDay} />
    ) : null;
  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">
          {/* A feedback station: the check-in leads (it is the thing to do
              before training and needs no training station), then the card
              over its skeleton. */}
          {feedbackStation && checkInRows}
          {/* A feedback station (no training station left for it, or a
              refused one): one card says trainings aren't saved here and
              offers Feedback training — and, in the left-most one, a station.
              No schedule, no past-workout log: they save. */}
          {feedbackStation && (
            <NoTrainingStationCard
              onFeedbackTraining={onFeedbackTraining}
              offerStation={offerStation}
            />
          )}
          {/* Recordings that are only on this device (no cloud storage):
              points at Settings → Videos on this device until acted on. */}
          <DeviceVideosCard />
          {/* An athlete's lead opens the screen. A coach's is one row about
              themselves and follows the card about their athletes. */}
          {ownDay && lead}
          {/* 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 training station. */}
          {!feedbackStation && checkInRows}
          {/* Prominent "log a past workout" entrance — first element under the
              header, above today's list. */}
          {!ownDay && logPast}
          {!feedbackStation && loading && (
            <p className="body-normal text-foreground-muted">{t("Loading…")}</p>
          )}
          {!feedbackStation && !loading && workouts && (
            <WorkoutsTodayList
              workouts={workouts}
              onSelect={onSelectWorkout}
              unavailable={scheduleUnavailable}
              emptyAction={{ label: t("Try again"), onClick: onRefresh }}
            />
          )}
          {ownDay && logPast}
        </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 />

      {/* No FAB at a feedback station (or on a locked device): its menu
          would only repeat the card's Start feedback training. */}
      {showFab && !feedbackStation && (
        <CreateWorkoutFab
          className={fabClassName}
          onCreateNew={onCreateNew}
          onOpenLibrary={onOpenLibrary}
          onFeedbackTraining={onFeedbackTraining}
        />
      )}
    </div>
  );
}

// Answering the daily check-in for athletes without a login of their own — see
// `AthletesCheckInRow`. Someone with no email never sees a prompt, 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.
export type CheckInCardConfig = {
  /** Those known to still owe a check-in today. Empty hides the row. */
  athletes: readonly UserReducedReturnDto[];
  checkInEnabled: boolean;
  onCheckInAthlete: (athlete: UserReducedReturnDto) => void;
};

// 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,
  quiet = false,
}: {
  onClick: () => void;
  /** Under the schedule on an athlete's own day: one row, no filled button. */
  quiet?: boolean;
}) {
  const { t } = useTranslation();
  if (quiet) {
    return (
      <button
        type="button"
        onClick={onClick}
        className="flex min-h-14 w-full items-center gap-3 rounded-2xl border border-surface-stroke bg-surface-base px-4 py-3 text-left hover:bg-surface-base-muted active:bg-surface-base-muted"
      >
        <span className="min-w-0 flex-1">
          <span className="body-prominent block text-foreground-default">
            {t("Log a past workout")}
          </span>
          <span className="body-small block text-foreground-muted">
            {t("Trained without the app? Enter the sets you completed.")}
          </span>
        </span>
        <ChevronRightIcon className="size-4 shrink-0 text-foreground-muted" />
      </button>
    );
  }
  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>
  );
}
