"use client";

import { useMemo, useState } from "react";
import { WELLNESS_METRIC_KEYS } from "@enode/core/metrics/wellness";
import { useTranslation } from "@enode/core/translations/hooks";
import {
  WELLNESS_SCORE_RANGE,
  WELLNESS_TREND_DEFAULTS,
  type WellnessDayStatus,
  type WellnessTrend,
} from "@enode/core/wellness/trend";
import {
  WellnessTrendChart,
  type WellnessTrendTone,
} from "@enode/ui/charts/wellness-trend-chart";
import { RequireData } from "@enode/ui/feedback/require-data";
import { WellnessMeasureIcon } from "@enode/ui/icons/wellness-measure-icon";
import { SegmentedPicker } from "@enode/ui/segmented-picker";
import { MEASURE_MAX, rampOf, useMeasureNames } from "./measure-words";
import { useReadinessHistory } from "./use-readiness-history";
import { trendTickIndices, type MeasuresToday } from "./week";
import { YourWeekSheet } from "./your-week-sheet";

// "Your trend": the athlete's own check-in totals over a month or a quarter,
// against their usual range — the chart the coach has in the portal's user
// drawer, and under it today's five answers.
//
// Nothing is read until the sheet opens: the body, and with it the request, is
// mounted only then.

type HistoryDays = 30 | 90;

const Y_TICKS = [5, 10, 15, 20, 25];

// The coach's chart marks a day far under the range in red. The athlete's own
// view never does — readiness speaks in green and amber only, as the card does.
const TONE: Record<WellnessDayStatus, WellnessTrendTone> = {
  usual: "usual",
  lower: "lower",
  muchLower: "lower",
  noBaseline: "neutral",
  missing: "neutral",
};

export function ReadinessHistorySheet({
  open,
  onClose,
  measures,
}: {
  open: boolean;
  onClose: () => void;
  /** Today's five answers, or null before they can be read. */
  measures: MeasuresToday | null;
}) {
  const { t } = useTranslation();
  return (
    <YourWeekSheet open={open} onClose={onClose} title={t("Your trend")}>
      {open && <History measures={measures} />}
    </YourWeekSheet>
  );
}

function History({ measures }: { measures: MeasuresToday | null }) {
  const { t } = useTranslation();
  const [days, setDays] = useState<HistoryDays>(30);
  const { trend, gate, retry } = useReadinessHistory(days);

  const body = trend ? (
    <HistoryBody trend={trend} days={days} measures={measures} />
  ) : (
    <ChartSkeleton />
  );

  return (
    <div className="flex flex-col gap-4">
      <div className="flex">
        <SegmentedPicker
          ariaLabel={t("Days shown")}
          value={days}
          onChange={setDays}
          options={[
            { value: 30, label: t("30 days") },
            { value: 90, label: t("90 days") },
          ]}
        />
      </div>
      {gate ? (
        <RequireData
          requirements={[{ state: gate, label: t("the daily check-ins") }]}
          onRetry={retry}
          showStaleHint
          loading={<ChartSkeleton />}
        >
          {body}
        </RequireData>
      ) : (
        body
      )}
    </div>
  );
}

function ChartSkeleton() {
  return (
    <div
      aria-busy="true"
      className="aspect-[2/1] w-full animate-pulse rounded-xl bg-surface-base-muted"
    />
  );
}

function HistoryBody({
  trend,
  days,
  measures,
}: {
  trend: WellnessTrend;
  days: HistoryDays;
  measures: MeasuresToday | null;
}) {
  const { t, locale } = useTranslation();
  const dayFormat = useMemo(
    () =>
      new Intl.DateTimeFormat(locale, {
        weekday: "short",
        day: "numeric",
        month: "short",
      }),
    [locale],
  );
  const tickFormat = useMemo(
    () => new Intl.DateTimeFormat(locale, { day: "numeric", month: "short" }),
    [locale],
  );

  if (trend.checkInDays === 0) {
    return (
      <div className="flex flex-col gap-1 rounded-2xl border border-surface-stroke bg-surface-base p-4">
        <p className="body-prominent text-foreground-default">
          {t("No check-ins yet")}
        </p>
        <p className="body-normal text-foreground-muted">
          {t(
            "Five quick questions before training. After seven check-ins every day is compared with your own normal.",
          )}
        </p>
      </div>
    );
  }

  const last = trend.days.length - 1;
  const chartDays = trend.days.map((day) => ({
    value: day.value,
    band: day.band,
    tone: TONE[day.status],
    title: dayFormat.format(day.date),
    detail:
      day.value === null
        ? t("No check-in")
        : t("{total} of {max}", {
            total: day.value,
            max: WELLNESS_SCORE_RANGE.max,
          }),
  }));
  const axisLabels = trendTickIndices(trend.days.length).map((index) => ({
    index,
    text: index === last ? t("Today") : tickFormat.format(trend.days[index].date),
  }));
  const hasRange = trend.days.some((day) => day.band !== null);
  const needed = WELLNESS_TREND_DEFAULTS.minBaseline;

  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-col gap-3 rounded-2xl border border-surface-stroke bg-surface-base p-4">
        <WellnessTrendChart
          days={chartDays}
          domain={WELLNESS_SCORE_RANGE}
          yTicks={Y_TICKS}
          axisLabels={axisLabels}
          highlightIndex={trend.latest ? trend.days.indexOf(trend.latest) : null}
          ariaLabel={t("Your check-in totals over the last {count} days", {
            count: days,
          })}
          className="aspect-[2/1] w-full"
        />
        <p className="body-small text-foreground-muted">
          {hasRange
            ? t(
                "The shaded band is your usual range — your own last four weeks.",
              )
            : t("Your normal is still forming · {count} of 7 check-ins", {
                count: Math.min(trend.baselineCount, needed),
              })}
        </p>
      </div>
      <TodaysAnswers measures={measures} />
    </div>
  );
}

/** Today's five answers, one row each: the measure and its level, 1–5. */
function TodaysAnswers({ measures }: { measures: MeasuresToday | null }) {
  const { t } = useTranslation();
  const names = useMeasureNames();
  const steps = Array.from({ length: MEASURE_MAX }, (_, index) => index + 1);
  return (
    <section className="flex flex-col gap-2">
      <h2 className="stat-small uppercase tracking-[0.08em] text-foreground-muted">
        {t("Today's answers")}
      </h2>
      <ul className="flex flex-col rounded-2xl border border-surface-stroke bg-surface-base px-4">
        {WELLNESS_METRIC_KEYS.map((key) => {
          const value = measures?.[key] ?? null;
          return (
            <li
              key={key}
              className="flex min-h-11 items-center gap-3 border-b border-surface-stroke last:border-b-0"
              aria-label={
                value === null
                  ? names[key]
                  : t("{measure}: {value} of {max}", {
                      measure: names[key],
                      value,
                      max: MEASURE_MAX,
                    })
              }
            >
              <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="body-normal min-w-0 flex-1 truncate text-foreground-default"
              >
                {names[key]}
              </span>
              <span aria-hidden="true" className="flex items-end gap-1">
                {steps.map((step) => (
                  <span
                    key={step}
                    className="h-3 w-1.5 rounded-full bg-surface-base-muted"
                    style={
                      value !== null && step <= value
                        ? { backgroundColor: rampOf(value) }
                        : undefined
                    }
                  />
                ))}
              </span>
            </li>
          );
        })}
      </ul>
    </section>
  );
}
