"use client";

import type { ComponentType, ReactNode } from "react";
import { useProfileImage } from "@enode/core/profile-images/hooks";
import { useTranslation } from "@enode/core/translations/hooks";
import { AthleteAvatar } from "@enode/ui/athlete-avatar";

import {
  CheckCircleFillIcon,
  CounterclockwiseArrowsIcon,
  DumbbellFillIcon,
  ExclamationTriangleFillIcon,
  MinusIcon,
  PersonFillIcon,
  PlusIcon,
  ScaleMassFillIcon,
  XIcon,
} from "./icons";

// Shared layout for the active-tracking recommendation cards. Two shapes:
//   - `RecommendationCard`      — one full-width action: a circled icon, a
//     vertical divider, then the main space (action text → big element → sub).
//   - `ChoiceRecommendationCard`— two compact actions side by side, split by an
//     "OR" separator (e.g. switch athlete OR start the next exercise).
// Every card carries an X to dismiss (top-right). Presentational only — the
// caller passes resolved strings + the tap handlers. Typography uses the
// design-system tokens (no ad-hoc sizes).

// Reversible: hide the top-left badge pill so the card is vertically thinner;
// the dismiss X then floats in the top-right corner (nudged down to clear the
// rounded edge) instead of riding the badge row. Flip to true to bring the
// badge back (badge + X share a top row).
const SHOW_BADGE = false;

// Reversible: tint the variant icon (+ load badge) platinum green and render the
// action text muted. The icon uses the card-tuned `-bright` accent so it lifts
// off the platinum tint in dark mode. Flip to false for the original scheme
// (red-orange icon, muted action text).
const ICON_PLATINUM_ACTION_RED = true;

// Reversible: replace the flat platinum-disabled surface + faint white sheen
// with a two-stop theme-aware gradient (lighter sage in light mode, darker teal
// in dark mode — see `--rec-card-from` / `--rec-card-to` in design-system.css).
// Flip to false for the original flat surface.
const CARD_GRADIENT_SURFACE = true;
const CARD_GRADIENT_SURFACE_CLASS = CARD_GRADIENT_SURFACE
  ? "bg-[linear-gradient(to_bottom,var(--rec-card-from),var(--rec-card-to))]"
  : "bg-foreground-platinum-green-disabled bg-gradient-to-b from-white/[0.07] to-transparent";

// Reversible trial of the card surface (the light sage gradient darkened
// toward its foot and, with the translucent ring, blurred into its own drop
// shadow on a light screen):
// - "deepGreen": plain Deep Green (`--brand-deep-green`), identical in light
//   and dark, like the tablet rail. The card renders as a `.theme-dark`
//   subtree, so text, divider, "OR" chip and hover take their dark-surface
//   values; icon and circle turn white; the shadow keeps the light values.
// - "platinum": flat Platinum Green (`--surface-platinum-green`, the brand book's
//   #dae9e1) with a solid stroke and a quiet shadow; a white icon circle with
//   the Deep Green glyph. Dark mode gets the flat dark teal.
// - "gradient": the sage gradient card as it was.
type CardLook = "deepGreen" | "platinum" | "gradient";
// Widened on purpose so every look stays reachable (and type-checked).
const CARD_LOOK = "deepGreen" as CardLook;
const DEEP_GREEN_CARD = CARD_LOOK === "deepGreen";
const PLATINUM_CARD = CARD_LOOK === "platinum";

const CARD_SHELL = DEEP_GREEN_CARD
  ? "theme-dark bg-brand-deep-green text-white shadow-[0_1px_3px_rgba(0,0,0,0.12),0_6px_16px_rgba(28,71,68,0.18)]"
  : PLATINUM_CARD
    ? "bg-(--surface-platinum-green) ring-1 ring-(--surface-platinum-green-stroke) shadow-[0_1px_3px_rgba(0,0,0,0.06)]"
    : `${CARD_GRADIENT_SURFACE_CLASS} shadow-floating ring-1 ring-foreground-platinum-green/30`;

// What sits ON the card surface and must match it (the +/− badge's ring, the
// "OR" chip that masks its divider).
const CARD_MATCH_RING = DEEP_GREEN_CARD
  ? "ring-brand-deep-green"
  : PLATINUM_CARD
    ? "ring-(--surface-platinum-green)"
    : "ring-foreground-platinum-green-disabled";
const CARD_MATCH_BG = DEEP_GREEN_CARD
  ? "bg-brand-deep-green"
  : PLATINUM_CARD
    ? "bg-(--surface-platinum-green)"
    : "bg-foreground-platinum-green-disabled";

// Text on the card. On Deep Green it is green-tinted (`--on-brand-deep-green`
// for labels and the dismiss X, `-muted` for secondary lines, all ≥ 4.5:1)
// instead of white at an opacity — grey on colour reads dull, and the 50 %
// context line fell to 3.8:1.
const CARD_TEXT_LABEL = DEEP_GREEN_CARD ? "text-on-brand-deep-green" : "text-foreground-default/70";
const CARD_TEXT_SECONDARY = DEEP_GREEN_CARD
  ? "text-on-brand-deep-green-muted"
  : "text-foreground-default/70";
const CARD_TEXT_CONTEXT = DEEP_GREEN_CARD
  ? "text-on-brand-deep-green-muted"
  : "text-foreground-default/50";
const CARD_TEXT_OR = DEEP_GREEN_CARD ? "text-on-brand-deep-green-muted" : "text-foreground-default/60";
// The action line ("Switch to", "Increase load").
const CARD_TEXT_ACTION = DEEP_GREEN_CARD
  ? "text-on-brand-deep-green"
  : ICON_PLATINUM_ACTION_RED
    ? "text-foreground-muted"
    : "text-foreground-default/70";

export type RecVariant =
  | "athlete"
  | "exercise"
  | "superset"
  | "load"
  | "loadIncrease"
  | "loadDecrease"
  | "complete"
  | "stop";

// One target rendered as an icon + main space. `main`/`sub`/`pills` are nodes
// so callers can compose richer values (e.g. "82.5 kg · 2 RIR"). `actionText`
// is optional (an informational card like the velocity-drop hint has none);
// `onClick` is optional too — without it the row is non-interactive.
export type RecAction = {
  variant: RecVariant;
  actionText?: string;
  main: ReactNode;
  sub?: ReactNode;
  pills?: ReactNode;
  // Athlete variant only: when the athlete has a loaded profile image it
  // replaces the person glyph inside the circle. Falls back to the glyph.
  avatar?: { userID: string; name: string };
  // A small element shown just right of the icon circle (e.g. the load
  // up/down direction arrow).
  adornment?: ReactNode;
  onClick?: () => void;
};

const VARIANT_ICON: Record<RecVariant, ComponentType<{ className?: string }>> = {
  athlete: PersonFillIcon,
  exercise: DumbbellFillIcon,
  superset: CounterclockwiseArrowsIcon,
  load: ScaleMassFillIcon,
  // The load up/down variants reuse the scale glyph; IconCircle overlays a
  // +/− badge to convey the direction.
  loadIncrease: ScaleMassFillIcon,
  loadDecrease: ScaleMassFillIcon,
  complete: CheckCircleFillIcon,
  stop: ExclamationTriangleFillIcon,
};

// A single full-width recommendation card.
export function RecommendationCard({
  badge,
  context,
  onDismiss,
  action,
}: {
  badge: ReactNode;
  context?: string | null;
  onDismiss?: () => void;
  action: RecAction;
}) {
  return (
    <Shell badge={badge} context={context} onDismiss={onDismiss}>
      <ActionRow action={action} compact={false} />
    </Shell>
  );
}

// A two-option recommendation card: two compact actions split by "OR".
export function ChoiceRecommendationCard({
  badge,
  context,
  onDismiss,
  left,
  right,
}: {
  badge: ReactNode;
  context?: string | null;
  onDismiss?: () => void;
  left: RecAction;
  right: RecAction;
}) {
  return (
    <Shell badge={badge} context={context} onDismiss={onDismiss}>
      <div className="flex items-stretch gap-1">
        <div className="min-w-0 flex-1">
          <ActionRow action={left} compact />
        </div>
        <OrSeparator />
        <div className="min-w-0 flex-1">
          <ActionRow action={right} compact />
        </div>
      </div>
    </Shell>
  );
}

function Shell({
  badge,
  context,
  onDismiss,
  children,
}: {
  badge: ReactNode;
  context?: string | null;
  onDismiss?: () => void;
  children: ReactNode;
}) {
  const { t } = useTranslation();
  const dismiss = onDismiss && (
    <button
      type="button"
      onClick={onDismiss}
      aria-label={t("Dismiss")}
      className={
        SHOW_BADGE
          ? `flex size-7 shrink-0 items-center justify-center rounded-full ${CARD_TEXT_LABEL} hover:bg-foreground-default/10 ${
              context ? "" : "ml-auto"
            }`
          : `absolute right-3 top-4 z-10 flex size-7 items-center justify-center rounded-full ${CARD_TEXT_LABEL} hover:bg-foreground-default/10`
      }
    >
      <XIcon className="size-4" />
    </button>
  );
  return (
    <div className={`relative w-full max-w-2xl rounded-2xl p-3 ${CARD_SHELL}`}>
      {SHOW_BADGE ? (
        <div className="flex items-center gap-2">
          <span className="stat-small inline-flex items-center gap-1 rounded-md bg-foreground-platinum-green px-2.5 py-1 font-semibold uppercase tracking-wide text-white">
            {badge}
          </span>
          {context && (
            <span className={`body-small ml-auto truncate ${CARD_TEXT_CONTEXT}`}>
              {context}
            </span>
          )}
          {dismiss}
        </div>
      ) : (
        <>
          {context && (
            <span className={`body-small block truncate pr-9 ${CARD_TEXT_CONTEXT}`}>
              {context}
            </span>
          )}
          {dismiss}
        </>
      )}
      {SHOW_BADGE ? children : <div className="pr-7">{children}</div>}
    </div>
  );
}

// The icon → divider → main-space row. `compact` shrinks the circle + type and
// drops the divider for the side-by-side choice columns.
function ActionRow({
  action,
  compact,
}: {
  action: RecAction;
  compact: boolean;
}) {
  const { variant, actionText, main, sub, pills, avatar, adornment, onClick } =
    action;
  const content = (
    <>
      <IconCircle variant={variant} compact={compact} avatar={avatar} />
      {adornment && (
        <span className="flex shrink-0 items-center self-center">
          {adornment}
        </span>
      )}
      {!compact && (
        <div className="w-px shrink-0 self-stretch bg-foreground-default/10" />
      )}
      <div className="min-w-0 flex-1 self-center">
        {pills && <div className="mb-1.5">{pills}</div>}
        {actionText && (
          <span
            className={`block font-semibold ${CARD_TEXT_ACTION} ${
              compact ? "body-normal" : "heading-normal"
            }`}
          >
            {actionText}
          </span>
        )}
        <span
          className={`block truncate font-bold ${
            compact ? "heading-normal" : "heading-large tabular-nums"
          }`}
        >
          {main}
        </span>
        {sub && (
          <span className={`body-small mt-0.5 block ${CARD_TEXT_SECONDARY}`}>
            {sub}
          </span>
        )}
      </div>
    </>
  );
  // Informational rows (no `onClick`, e.g. the velocity-drop hint) render as a
  // plain, non-interactive container — no button affordance / hover.
  if (!onClick) {
    return <div className="flex w-full items-stretch gap-3 p-2">{content}</div>;
  }
  return (
    <button
      type="button"
      onClick={onClick}
      className="flex w-full items-stretch gap-3 rounded-xl p-2 text-left transition-colors hover:bg-foreground-default/5"
    >
      {content}
    </button>
  );
}

// The bordered circle around the variant's icon (red-orange glyph). For the
// athlete variant it shows the athlete's profile image instead — but only when
// one has loaded; otherwise it falls back to the person glyph.
function IconCircle({
  variant,
  compact,
  avatar,
}: {
  variant: RecVariant;
  compact: boolean;
  avatar?: { userID: string; name: string };
}) {
  // Safe with an undefined id (returns undefined); always called so hook order
  // stays stable.
  const image = useProfileImage(avatar?.userID);
  const ring = `relative flex shrink-0 items-center justify-center self-center rounded-full ${
    DEEP_GREEN_CARD
      ? "border border-white/25 bg-white/10"
      : PLATINUM_CARD
        ? "bg-surface-drawer/70"
        : "border border-foreground-platinum-green/60"
  } ${
    compact ? "size-10" : "size-14"
  }`;

  if (
    variant === "athlete" &&
    avatar &&
    image?.status === "loaded" &&
    image.src
  ) {
    return (
      <span className={`overflow-hidden ${ring}`}>
        <AthleteAvatar
          userID={avatar.userID}
          name={avatar.name}
          size={compact ? 40 : 56}
        />
      </span>
    );
  }

  // The load up/down variants overlay a +/− badge on the scale glyph; the
  // badge's ring matches the card surface so it reads as a separate chip.
  const BadgeGlyph =
    variant === "loadIncrease"
      ? PlusIcon
      : variant === "loadDecrease"
        ? MinusIcon
        : null;

  // On Deep Green the glyph is white and red-orange marks only what changes
  // or warns: the load +/− badge and the stop variant's warning glyph.
  const iconColor = DEEP_GREEN_CARD
    ? variant === "stop"
      ? "text-brand-red-orange"
      : "text-white"
    : ICON_PLATINUM_ACTION_RED
      ? "text-foreground-platinum-green-bright"
      : "text-brand-red-orange";
  const badgeColor = DEEP_GREEN_CARD
    ? "bg-foreground-red-orange"
    : ICON_PLATINUM_ACTION_RED
      ? "bg-foreground-platinum-green-bright"
    : "bg-foreground-red-orange";

  const Icon = VARIANT_ICON[variant];
  return (
    <span className={ring}>
      <Icon className={`${iconColor} ${compact ? "size-5" : "size-7"}`} />
      {BadgeGlyph && (
        <span
          className={`absolute bottom-0 right-0 flex items-center justify-center rounded-full text-white ring-2 ${CARD_MATCH_RING} ${badgeColor} ${
            compact ? "size-3.5" : "size-4"
          }`}
        >
          <BadgeGlyph className={compact ? "size-2" : "size-2.5"} />
        </span>
      )}
    </span>
  );
}

// Vertical line with a centered "OR" chip that masks the line (the chip's
// background matches the card surface).
function OrSeparator() {
  const { t } = useTranslation();
  return (
    <div className="relative mx-1 flex w-px shrink-0 items-center justify-center self-stretch bg-foreground-default/10">
      <span className={`stat-small absolute rounded-full ${CARD_MATCH_BG} px-1.5 py-0.5 uppercase ${CARD_TEXT_OR}`}>
        {t("or")}
      </span>
    </div>
  );
}
