"use client";

import { useTranslation } from "@enode/core/translations/hooks";
import { Button } from "@enode/ui/button";
import { CheckIcon, CloseXIcon, SpinnerIcon } from "@enode/ui/icons";
import { Sheet } from "@enode/ui/sheet";
import { changeableSessionIDs } from "./change-rating";
import type { SessionRpeState } from "./payload";
import { useRpeLabel } from "./rpe-label";
import { HEADER_ICON_BUTTON } from "@enode/ui/header-button";

// The confirmation after a session rating, drawn over the closed
// questionnaire. The one confirmation: the service's own "logged" panel is
// never seen in this app, because the sheet closes on submit.
//
// It exists because the interesting part of a rating is not the rating: the
// server works out which workout it belongs to and multiplies by that workout's
// recorded volume to produce a training load. That is the number worth showing,
// and it only exists once the write has come back.
//
// Which is also why there is a pending state. The service reports `submitted`
// the moment the athlete taps, and `saved` only after the round trip — a real
// window in which the rating is logged and the outcome is genuinely unknown.

/**
 * What became of the rating. Every branch is a sentence that must not
 * overclaim: a rating that matched no workout, or matched one with no recorded
 * sets, produces no training load at all — never a load of zero.
 */
function Outcome({ state }: { state: SessionRpeState }) {
  const { t, locale } = useTranslation();

  if (state.status === "pending") {
    return (
      <div className="flex items-center justify-center gap-2">
        <SpinnerIcon className="size-4 animate-spin text-foreground-muted" />
        <span className="body-small text-foreground-muted">{t("Saving…")}</span>
      </div>
    );
  }

  if (state.status === "failed") {
    return (
      <p className="body-normal text-center text-foreground-muted">
        {state.queued
          ? t("Not sent yet — kept on this device and sent when you're back online.")
          : t("This couldn't be saved. Your rating wasn't recorded.")}
      </p>
    );
  }

  const { sessionCount, trainingLoad } = state.result;

  // Stored against the athlete, but attached to nothing: no workout recorded in
  // the last day, or the one there was had already been rated.
  if (sessionCount === 0) {
    return (
      <p className="body-normal text-center text-foreground-muted">
        {t(
          "Saved. It wasn't matched to a workout, so there's no training load for it — either nothing was recorded in the last day, or that session was already rated.",
        )}
      </p>
    );
  }

  // A workout, but nothing to multiply by.
  if (trainingLoad === null) {
    return (
      <p className="body-normal text-center text-foreground-muted">
        {t(
          "Saved. No training load though — that session has no recorded sets or reps to weigh it against.",
        )}
      </p>
    );
  }

  return (
    <div className="flex w-full flex-col gap-1 rounded-2xl border border-surface-stroke bg-surface-base p-4 text-left">
      <span className="stat-small uppercase tracking-[0.08em] text-foreground-muted">
        {t("Training load")}
      </span>
      <span className="stat-large-digits text-foreground-default">
        {new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(
          trainingLoad,
        )}
      </span>
      {/* What the number is, in one line: the athlete met "training load" for
          the first time on this screen. */}
      <span className="body-small text-foreground-muted">
        {t(
          "{count, plural, one {Your rating × the work you recorded in # workout.} other {Your rating × the work you recorded in # workouts.}} It adds to your training load for the week.",
          { count: sessionCount },
        )}
      </span>
    </div>
  );
}

export function SessionRpeResultDrawer({
  state,
  onClose,
  onChange,
}: {
  /** Where the rating has got to, or null when nothing has been logged yet. */
  state: SessionRpeState | null;
  onClose: () => void;
  /**
   * Rate again, for exactly the sessions this rating was attached to — the
   * new rating then replaces it. Offered only while those sessions are known
   * (`changeableSessionIDs`).
   */
  onChange: (sessionIDs: readonly string[]) => void;
}) {
  const { t } = useTranslation();
  const rpeLabel = useRpeLabel();
  const changeable = changeableSessionIDs(state);

  return (
    <Sheet
      open={state !== null}
      onClose={onClose}
      slideFrom="bottom"
      ariaLabel={t("Session logged")}
      backdrop
      // Same insets as the questionnaire sheet it follows — this one opens
      // straight after it, so a header at a different height would read as the
      // screen jumping.
      className="flex flex-col bg-background pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]"
    >
      <header className="flex shrink-0 items-center justify-between gap-3 px-5 pt-4 pb-2">
        <h1 className="heading-normal">{t("Rate your session")}</h1>
        <button
          type="button"
          onClick={onClose}
          aria-label={t("Close")}
          className={HEADER_ICON_BUTTON}
        >
          <CloseXIcon className="size-5" />
        </button>
      </header>

      <div className="scrollbar-none flex min-h-0 flex-1 flex-col overflow-y-auto px-5 pb-6">
        {state && (
          <div className="mx-auto my-auto flex w-full max-w-sm flex-col items-center gap-4 text-center">
            <span className="flex size-14 items-center justify-center rounded-full bg-feedback-success-surface text-feedback-success">
              <CheckIcon className="size-6" />
            </span>
            <div className="flex flex-col gap-1">
              <h2 className="heading-large text-foreground-default">
                {t("Session logged")}
              </h2>
              <p className="body-normal text-foreground-muted">
                {t("Rated {rpe} out of 10 · {label}", {
                  rpe: state.payload.rpe,
                  label: rpeLabel(state.payload.rpe),
                })}
              </p>
            </div>

            <Outcome state={state} />

            <div className="flex flex-col items-center gap-2">
              <Button variant="primary" size="large" onClick={onClose}>
                {t("Done")}
              </Button>
              {changeable && (
                <Button
                  variant="tertiary"
                  size="large"
                  onClick={() => onChange(changeable)}
                >
                  {t("Change rating")}
                </Button>
              )}
            </div>
          </div>
        )}
      </div>
    </Sheet>
  );
}
