"use client";

import { memo, useState } from "react";
import { useTranslation } from "@enode/core/translations/hooks";
import { ChevronDownIcon } from "@enode/ui/icons";
import { SegmentedBar } from "@enode/ui/charts/segmented-bar";
import { WeeklyGoalBadge } from "./weekly-goal-banner";
import type { MuscleUsageRowVm, MuscleUsageVm } from "./athlete-summary-view-model";
import { LOOK } from "@enode/ui/live/look";

// Portal-local card: the per-muscle usage bars (iOS StatisticElementMuscleUsage
// / MuscleUsageCell), without the per-muscle icons — they cost a 40px column
// per row for no information the name doesn't carry. One row per muscle: name +
// "sets / target" + an orange progress bar (full = this muscle's target) + a %
// label, collapsible.
//
// Ordering and the bar arithmetic both happen in
// `buildMuscleUsageVm`; this component only paints and owns the collapse.

// Rows shown while collapsed; the rest sit behind "show more". A row count
// rather than a height cap, so the collapsed card never cuts a row in half.
const COLLAPSED_ROWS = 5;

export const MuscleUsageCard = memo(function MuscleUsageCard({
  vm,
  showPaceBadges = true,
}: {
  vm: MuscleUsageVm;
  /** The per-row pace badge ("Behind pace") — judged against today, so it is
   *  only meaningful for the running week. */
  showPaceBadges?: boolean;
}) {
  const { t } = useTranslation();
  const [showAll, setShowAll] = useState(false);

  const title = vm.title || t("Muscle usage");

  return (
    <section className={`${LOOK.panel} p-4`}>
      <div className="flex items-center justify-between gap-3">
        <h3 className="heading-section">{title}</h3>
        {showAll && (
          <button
            type="button"
            onClick={() => setShowAll(false)}
            className="text-foreground-muted transition-colors hover:text-foreground-default"
            aria-label={t("Show less")}
          >
            <ChevronDownIcon className="size-5 rotate-180" />
          </button>
        )}
      </div>
      {vm.detail ? (
        <p className="body-small mt-1 text-foreground-muted">{vm.detail}</p>
      ) : null}

      <div className="mt-4 flex flex-col gap-4">
        {(showAll ? vm.rows : vm.rows.slice(0, COLLAPSED_ROWS)).map((row, i) => (
          <MuscleUsageRow
            key={row.muscleId ?? i}
            row={row}
            showPaceBadge={showPaceBadges}
          />
        ))}
      </div>
      {!showAll && vm.rows.length > COLLAPSED_ROWS && (
        <button
          type="button"
          onClick={() => setShowAll(true)}
          className="clickable-small mt-3 flex w-full items-center justify-center gap-1 text-foreground-muted transition-colors hover:text-foreground-default"
        >
          {t("Show all {count} muscles", { count: vm.rows.length })}
          <ChevronDownIcon className="size-4" />
        </button>
      )}
    </section>
  );
});

const MuscleUsageRow = memo(function MuscleUsageRow({
  row,
  showPaceBadge,
}: {
  row: MuscleUsageRowVm;
  showPaceBadge: boolean;
}) {
  const { t } = useTranslation();
  const hasTarget = row.target != null;
  // Single solid Deep Green fill (actual sets) over a full-width muted track;
  // the fill clamps at 100% when over target. Deep Green like the session
  // drawer's muscle bars: red-orange marks highlights and warnings, not volume.
  const segments = [
    { value: row.setCount, color: "var(--foreground-platinum-green-bright)" },
  ];

  return (
    <div>
      <div>
        <div className="flex items-baseline justify-between gap-2">
          <div className="flex min-w-0 items-center gap-2">
            <span className="body-prominent truncate text-foreground-default">
              {row.name ?? "—"}
            </span>
            {showPaceBadge && (
              <WeeklyGoalBadge setCount={row.setCount} target={row.target} />
            )}
          </div>
          <div className="flex shrink-0 items-baseline gap-2 tabular-nums text-foreground-muted">
            <span className="stat-small">
              {hasTarget
                ? t("{done} / {target} sets", {
                    done: Math.round(row.setCount),
                    target: Math.round(row.target as number),
                  })
                : t("{count, plural, one {# set} other {# sets}}", {
                    count: Math.round(row.setCount),
                  })}
            </span>
            {row.completionPercent != null && (
              <span className="stat-small">{row.completionPercent}%</span>
            )}
          </div>
        </div>
        <SegmentedBar className="mt-1.5" segments={segments} max={row.scaleMax} />
      </div>
    </div>
  );
});

export function MuscleUsageCardSkeleton() {
  return (
    <section
      aria-busy="true"
      className={`${LOOK.panel} p-4`}
    >
      <div className="h-5 w-36 animate-pulse rounded-md bg-surface-base-muted" />
      <div className="mt-4 flex flex-col gap-4">
        {Array.from({ length: 4 }).map((_, i) => (
          <div key={i}>
            <div className="space-y-1.5">
              <span className="block h-4 w-32 animate-pulse rounded bg-surface-base-muted" />
              <span className="block h-2 w-full animate-pulse rounded-full bg-surface-base-muted" />
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}
