"use client";

import { useMemo, useState, type ReactNode } from "react";
import { WELLNESS_METRIC_KEYS } from "@enode/core/metrics/wellness";
import { useTranslation } from "@enode/core/translations/hooks";
import { Button } from "@enode/ui/button";
import { ProgressRing } from "@enode/ui/charts/progress-ring";
import { SunMaxFillIcon } from "@enode/ui/icons";
import { WellnessMeasureIcon } from "@enode/ui/icons/wellness-measure-icon";
import { HowToReadSheet } from "./how-to-read-sheet";
import { MEASURE_MAX, rampOf, useMeasureNames } from "./measure-words";
import { ReadinessHistorySheet } from "./readiness-history-sheet";
import type { LoadWeek } from "./use-your-week";
import type { ReadinessVerdict } from "./verdict";
import { loadBar, type MeasuresToday, type ReadinessWeek } from "./week";

// "Your week": what the daily check-in and the session rating add up to, shown
// to the person who answers them.
//
// Both questionnaires used to be a one-way street — asked every day, and only
// the coach ever saw the result (the portal's user drawer). This card is the
// way back, from the very same trends the coach reads.
//
// The readiness part is laid out like the native app's Readiness card
// (WellnessReadinessLane there): the total in a ring, the athlete's own normal
// beside it, and one column per measure under its mark. Before today's
// check-in the ring is empty around a sun, and the card asks. Once there is a
// normal to compare with, the card says where today sits against it.
//
// Three quiet ways lead on from it: the trend over a month or a quarter, a
// second go at today's check-in, and "How to read this".
//
// Each part appears only when its feature is on for the account, and the card
// only when at least one is — the host decides and passes `null` otherwise.

const SCORE_MAX = 25;

// The readiness language: green above the normal, amber below it. Never red —
// a day under one's own average is information, not an alarm.
const VERDICT_COLOR: Record<ReadinessVerdict, string> = {
  fresher: "var(--foreground-platinum-green-bright)",
  about: "var(--foreground-default)",
  slightlyBelow: "var(--feedback-warning)",
  below: "var(--feedback-warning)",
};

export type YourWeekCardProps = {
  /** Null hides the readiness part (check-ins off, or not readable yet). */
  readiness: ReadinessWeek | null;
  /** Today's five answers, or null before they can be read. */
  measures: MeasuresToday | null;
  /** Null hides the training-load part. */
  load: LoadWeek | null;
  /**
   * Whether today's check-in is known to be done — from the app's own record,
   * which knows before the measurement has reached the server.
   */
  checkedInToday: boolean;
  /** Opens today's check-in. Absent when there is none to offer. */
  onCheckIn?: () => void;
  /**
   * Opens the check-in once more on a day that already has one — the later
   * answers replace the first. Absent when there is nothing to change.
   */
  onChangeCheckIn?: () => void;
  /** An athlete's coach reads the same numbers; said only where it is true. */
  sharedWithCoach: boolean;
  /** Without the card's own frame and title — inside a sheet that has both. */
  bare?: boolean;
};

export function YourWeekCard({
  readiness,
  measures,
  load,
  checkedInToday,
  onCheckIn,
  onChangeCheckIn,
  sharedWithCoach,
  bare = false,
}: YourWeekCardProps) {
  const { t } = useTranslation();
  const [howToReadOpen, setHowToReadOpen] = useState(false);
  if (!readiness && !load) return null;
  const howToRead = (
    <QuietLink onClick={() => setHowToReadOpen(true)}>
      {t("How to read this")}
    </QuietLink>
  );
  return (
    <section
      className={
        bare
          ? "flex flex-col gap-4"
          : "flex flex-col gap-4 rounded-2xl border border-surface-stroke bg-surface-base p-4"
      }
    >
      {(!bare || sharedWithCoach) && (
        <div className="flex items-baseline justify-between gap-3">
          {!bare && <h3 className="heading-normal">{t("Your week")}</h3>}
          {sharedWithCoach && (
            <span className="body-small text-foreground-muted">
              {t("Your coach sees this too.")}
            </span>
          )}
        </div>
      )}

      {readiness && (
        <Readiness
          readiness={readiness}
          measures={measures}
          checkedInToday={checkedInToday}
          onCheckIn={onCheckIn}
          onChangeCheckIn={onChangeCheckIn}
          // With a load part below, the explanation closes the whole card
          // instead of the readiness part.
          howToRead={load ? null : howToRead}
        />
      )}
      {readiness && load && <div className="h-px bg-surface-stroke" />}
      {load && <Load load={load} />}

      {/* Pulled in by the links' own height: a full touch target each, but
          a line of text to the eye. */}
      {(load || !readiness) && <div className="-my-2 flex">{howToRead}</div>}
      <HowToReadSheet
        open={howToReadOpen}
        onClose={() => setHowToReadOpen(false)}
        readiness={readiness !== null}
        load={load !== null}
        sharedWithCoach={sharedWithCoach}
      />
    </section>
  );
}

function Eyebrow({ children }: { children: string }) {
  return (
    <span className="stat-small uppercase tracking-[0.08em] text-foreground-muted">
      {children}
    </span>
  );
}

/** A way on from the card that does not compete with its numbers: a line of
 *  text, a full touch target high. */
function QuietLink({
  onClick,
  children,
}: {
  onClick: () => void;
  children: string;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="clickable-small flex min-h-11 items-center text-foreground-muted underline decoration-surface-stroke underline-offset-4 hover:text-foreground-default"
    >
      {children}
    </button>
  );
}

// Title and sentence per verdict, the native app's words. Explicit literals so
// every one is extractable.
function useVerdictWords(): Record<
  ReadinessVerdict,
  { title: string; detail: string }
> {
  const { t } = useTranslation();
  return {
    fresher: {
      title: t("Fresher than your normal"),
      detail: t("Above your own recent average — a good day to push."),
    },
    about: {
      title: t("About your normal"),
      detail: t("Right around your usual — nothing unusual today."),
    },
    slightlyBelow: {
      title: t("A little below your normal"),
      detail: t("Slightly under your usual — train, but watch how it feels."),
    },
    below: {
      title: t("Below your normal"),
      detail: t("Well under your usual — train, but listen to how it feels."),
    },
  };
}

function Readiness({
  readiness,
  measures,
  checkedInToday,
  onCheckIn,
  onChangeCheckIn,
  howToRead,
}: {
  readiness: ReadinessWeek;
  measures: MeasuresToday | null;
  checkedInToday: boolean;
  onCheckIn?: () => void;
  onChangeCheckIn?: () => void;
  /** The "How to read this" link, when it belongs on this part's line. */
  howToRead: ReactNode;
}) {
  const { t, locale } = useTranslation();
  const names = useMeasureNames();
  const verdictWords = useVerdictWords();
  const [historyOpen, setHistoryOpen] = useState(false);
  const oneDecimal = useMemo(
    () =>
      new Intl.NumberFormat(locale, {
        minimumFractionDigits: 1,
        maximumFractionDigits: 1,
      }),
    [locale],
  );
  const weekday = useMemo(
    () => new Intl.DateTimeFormat(locale, { weekday: "narrow" }),
    [locale],
  );
  const longDay = useMemo(
    () => new Intl.DateTimeFormat(locale, { weekday: "long" }),
    [locale],
  );
  const total = readiness.today;
  const verdict = readiness.verdict;
  const below = verdict === "slightlyBelow" || verdict === "below";

  return (
    <div className="flex flex-col gap-4">
      <div className="flex items-center gap-4">
        <ProgressRing
          value={total === null ? 0 : total / SCORE_MAX}
          size={84}
          lineWidth={8}
          color={
            below
              ? "var(--feedback-warning)"
              : "var(--foreground-platinum-green-bright)"
          }
          trackColor="var(--surface-base-muted)"
        >
          {total === null ? (
            // No number to show yet: the sun says "this morning's question".
            <SunMaxFillIcon
              className={`size-7 ${
                checkedInToday
                  ? "text-foreground-platinum-green-bright"
                  : "text-foreground-muted"
              }`}
            />
          ) : (
            <span className="flex items-baseline">
              <span className="stat-large-digits text-foreground-default">
                {total}
              </span>
              <span className="stat-small text-foreground-muted">
                /{SCORE_MAX}
              </span>
            </span>
          )}
        </ProgressRing>
        <div className="flex min-w-0 flex-col gap-0.5">
          <Eyebrow>{t("Readiness")}</Eyebrow>
          <p className="heading-normal text-foreground-default">
            {total !== null
              ? t("{total} of {max} today", { total, max: SCORE_MAX })
              : checkedInToday
                ? // Sent a moment ago and not yet readable from the server: say
                  // that it is done rather than ask again.
                  t("Checked in today")
                : t("How do you feel today?")}
          </p>
          {verdict && (
            <p className="body-small text-foreground-default">
              <span
                className="block font-semibold"
                style={{ color: VERDICT_COLOR[verdict] }}
              >
                {verdictWords[verdict].title}
              </span>
              {verdictWords[verdict].detail}
            </p>
          )}
          <p className="body-small text-foreground-muted">
            {readiness.normal !== null
              ? t(
                  "{count, plural, one {Your normal: {normal} · # check-in} other {Your normal: {normal} · # check-ins}}",
                  {
                    normal: oneDecimal.format(readiness.normal),
                    count: readiness.normalFrom,
                  },
                )
              : t(
                  "Your normal is still forming · {count} of 7 check-ins",
                  { count: Math.min(readiness.normalFrom, 7) },
                )}
          </p>
        </div>
      </div>

      {/* One column per measure, under its mark. Empty until today's answers
          are in — the marks stay, so the card has the same shape before and
          after the check-in. */}
      <ul className="grid grid-cols-5 gap-2">
        {WELLNESS_METRIC_KEYS.map((key) => {
          const value = measures?.[key] ?? null;
          return (
            <li
              key={key}
              className="flex min-w-0 flex-col items-center gap-1.5"
              aria-label={
                value === null
                  ? names[key]
                  : t("{measure}: {value} of {max}", {
                      measure: names[key],
                      value,
                      max: MEASURE_MAX,
                    })
              }
            >
              <span
                aria-hidden="true"
                className="flex h-9 w-2.5 items-end overflow-hidden rounded-full bg-surface-base-muted"
              >
                {value !== null && (
                  <span
                    className="w-full rounded-full"
                    style={{
                      height: `${(value / MEASURE_MAX) * 100}%`,
                      backgroundColor: rampOf(value),
                    }}
                  />
                )}
              </span>
              <span
                className="flex text-foreground-muted"
                style={value === null ? undefined : { color: rampOf(value) }}
              >
                <WellnessMeasureIcon measure={key} className="size-4" />
              </span>
              <span
                aria-hidden="true"
                className="stat-micro w-full truncate text-center uppercase tracking-[0.06em] text-foreground-muted"
              >
                {names[key]}
              </span>
            </li>
          );
        })}
      </ul>

      {onCheckIn && (
        <Button variant="primary" size="large" onClick={onCheckIn}>
          {t("Check in")}
        </Button>
      )}

      {/* The week, small: which of the last seven days have a check-in. */}
      <div className="flex items-center gap-3">
        <ul
          className="flex flex-1 items-center gap-1.5"
          aria-label={t("Last 7 days")}
        >
          {readiness.days.map((day) => (
            <li
              key={day.date}
              className="flex min-w-0 flex-1 flex-col items-center gap-1"
              aria-label={
                day.value === null
                  ? t("{day}: no check-in", { day: longDay.format(day.date) })
                  : t("{day}: {total} of {max}", {
                      day: longDay.format(day.date),
                      total: day.value,
                      max: SCORE_MAX,
                    })
              }
            >
              <span
                aria-hidden="true"
                className={`h-1.5 w-full rounded-full ${
                  day.value !== null
                    ? "bg-foreground-platinum-green-bright"
                    : day.isToday && !checkedInToday
                      ? "border border-dashed border-foreground-more-muted"
                      : "bg-surface-base-muted"
                }`}
              />
              <span
                aria-hidden="true"
                className={`stat-micro ${
                  day.isToday
                    ? "text-foreground-default"
                    : "text-foreground-more-muted"
                }`}
              >
                {weekday.format(day.date)}
              </span>
            </li>
          ))}
        </ul>
        <span className="body-small shrink-0 text-foreground-muted">
          {t("{count} of 7 days", { count: readiness.checkIns })}
        </span>
      </div>

      {/* One line of ways on, short enough to stay one line on a phone. */}
      <div className="-my-2 flex flex-wrap gap-x-5">
        <QuietLink onClick={() => setHistoryOpen(true)}>
          {t("Your trend")}
        </QuietLink>
        {onChangeCheckIn && (
          <QuietLink onClick={onChangeCheckIn}>
            {t("Edit check-in")}
          </QuietLink>
        )}
        {howToRead}
      </div>
      <ReadinessHistorySheet
        open={historyOpen}
        onClose={() => setHistoryOpen(false)}
        measures={measures}
      />
    </div>
  );
}

function Load({ load }: { load: LoadWeek }) {
  const { t, locale } = useTranslation();
  const number = useMemo(
    () => new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }),
    [locale],
  );
  const bar = loadBar(load.thisWeek, load.usualWeek);

  return (
    <div className="flex min-w-0 flex-col gap-2">
      <div className="flex items-baseline justify-between gap-3">
        <Eyebrow>{t("Training load")}</Eyebrow>
        {load.sessions > 0 && (
          <span className="stat-medium-digits text-foreground-default">
            {number.format(load.thisWeek)}
          </span>
        )}
      </div>
      {load.sessions === 0 ? (
        <p className="body-small text-foreground-muted">
          {t(
            "Rate a session after training and your load for the week shows here.",
          )}
        </p>
      ) : (
        <>
          <div className="relative h-2 rounded-full bg-surface-base-muted">
            <div
              className="h-full rounded-full bg-foreground-platinum-green-bright"
              style={{ width: `${bar.filled * 100}%` }}
            />
            {bar.usual !== null && (
              <div
                aria-hidden="true"
                className="absolute -top-1 h-4 w-0.5 rounded-full bg-foreground-default"
                style={{ left: `${bar.usual * 100}%` }}
              />
            )}
          </div>
          <p className="body-small text-foreground-muted">
            {load.usualWeek === null
              ? t(
                  "{count, plural, one {This week, from # rated session.} other {This week, from # rated sessions.}}",
                  { count: load.sessions },
                )
              : t(
                  "{count, plural, one {This week, from # rated session.} other {This week, from # rated sessions.}} The mark is your usual week: {usual}.",
                  {
                    count: load.sessions,
                    usual: number.format(load.usualWeek),
                  },
                )}
          </p>
        </>
      )}
    </div>
  );
}
