"use client";

import { useEffect, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "@enode/core/translations/hooks";
import { Button } from "./button";
import { ChevronRightIcon, XIcon } from "./icons";
import { useModalFocus } from "./use-modal-focus";

// Shared chrome for the "how it works" walkthroughs (Insights chart types,
// Profiles analyses, roster upload, exercise creation). They're all the same
// shape — a centered modal that either narrates a single flow (a guided carousel)
// or offers an overview of preview cards that open a per-item carousel — so the
// layout, motion and accent live here once, in @enode/ui, for both apps and
// Storybook. Accent is the brand's platinum green throughout (no red-orange);
// each feature area feeds its own copy, icons, mock illustrations and steps in.

// ─── Modal shell ─────────────────────────────────────────────────────────────

// Two screens in one scrim modal: an overview (all items as cards) and a
// per-item detail. `renderOverview`/`renderDetail` keep this agnostic to what an
// "item" is (a chart type, an analysis, …). Body-portalled; Escape / backdrop
// close. The screen fades on every overview↔detail switch.
//
// Single-flow mode (`singleFlow`): for a walkthrough with exactly one journey
// (roster upload, migration). There is no overview and no Back button — the
// modal opens straight into `renderFlow()` with just the close button above it.
type WalkthroughModalCommonProps = {
  open: boolean;
  // Heading shown on the overview screen (and the default dialog label source).
  title: string;
  ariaLabel: string;
  onClose: () => void;
  // A wider panel, for an overview that is a list of full sentences rather
  // than a grid of cards.
  wide?: boolean;
};

type WalkthroughModalOverviewProps<T extends string> = {
  singleFlow?: false;
  // Back-button label shown on a detail screen.
  backLabel: string;
  // Open straight into an item's detail, or null for the overview.
  initialSelected: T | null;
  renderOverview: (onSelect: (item: T) => void) => ReactNode;
  // `back` returns to the overview screen. Overview-based how-tos end their
  // detail tour with it (a "Back to overview" final action) instead of closing;
  // a detail with a forward CTA (e.g. Insights' "Create one") can ignore it.
  renderDetail: (selected: T, back: () => void) => ReactNode;
};

type WalkthroughModalSingleFlowProps = {
  singleFlow: true;
  // The one journey's content (typically a WalkthroughCarousel).
  renderFlow: () => ReactNode;
};

export function WalkthroughModal<T extends string>(
  props: WalkthroughModalCommonProps &
    (WalkthroughModalOverviewProps<T> | WalkthroughModalSingleFlowProps),
) {
  const { open, title, ariaLabel, onClose, wide = false } = props;
  const initialSelected = props.singleFlow ? null : props.initialSelected;
  const { t } = useTranslation();
  const [selected, setSelected] = useState<T | null>(initialSelected);
  // The panel takes the focus while the modal is open, Tab stays inside it,
  // and the focus returns to the opener on close.
  const panelRef = useRef<HTMLDivElement>(null);
  useModalFocus(panelRef, open);

  // Reset to the requested entry (overview vs a specific item) each time the
  // modal opens — it stays mounted across open/close, so seed on the false→true
  // transition (adjust-state-during-render, not an effect).
  const [wasOpen, setWasOpen] = useState(open);
  if (open !== wasOpen) {
    setWasOpen(open);
    if (open) setSelected(initialSelected);
  }

  useEffect(() => {
    if (!open) return;
    function onKeyDown(e: KeyboardEvent) {
      if (e.key === "Escape") onClose();
    }
    document.addEventListener("keydown", onKeyDown);
    return () => document.removeEventListener("keydown", onKeyDown);
  }, [open, onClose]);

  if (!open) return null;

  return createPortal(
    <div
      role="dialog"
      aria-modal="true"
      aria-label={ariaLabel}
      className="fixed inset-0 z-[120] flex items-start justify-center overflow-y-auto bg-black/50 p-4 md:p-8"
      onClick={onClose}
    >
      <div
        ref={panelRef}
        tabIndex={-1}
        className={`my-auto w-full rounded-2xl bg-surface-base p-5 shadow-2xl outline-none md:p-6 ${
          wide ? "max-w-3xl" : "max-w-2xl"
        }`}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="mb-4 flex items-center justify-between gap-3">
          {props.singleFlow ? (
            <span />
          ) : selected ? (
            // The global Button (neutral pill + leading back chevron) so the
            // back control reads as a real button, matching the app's button
            // system — not a bare text link next to the chromed close button.
            <Button
              variant="neutral"
              size="rounded"
              leadingIcon={<ChevronRightIcon className="size-4 rotate-180" />}
              onClick={() => setSelected(null)}
            >
              {props.backLabel}
            </Button>
          ) : (
            <h2 className="heading-section text-foreground-default">{title}</h2>
          )}
          <button
            type="button"
            onClick={onClose}
            aria-label={t("Close")}
            className="flex size-8 shrink-0 items-center justify-center rounded-full bg-surface-base text-foreground-muted shadow ring-1 ring-surface-stroke transition-colors hover:bg-surface-base-muted hover:text-foreground-default"
          >
            <XIcon className="size-4" />
          </button>
        </div>

        {/* Re-key by screen so switching overview↔detail fades in. */}
        <div key={selected ?? "overview"} className="fade-in">
          {props.singleFlow
            ? props.renderFlow()
            : selected
              ? props.renderDetail(selected, () => setSelected(null))
              : props.renderOverview((item) => setSelected(item))}
        </div>
      </div>
    </div>,
    document.body,
  );
}

// ─── Overview card ───────────────────────────────────────────────────────────

// A browsable card in the overview grid: glyph + name + the question it answers.
// Neutral by default; lifts and picks up the platinum accent on hover.
export function WalkthroughOverviewCard({
  icon,
  title,
  subtitle,
  onClick,
}: {
  icon: ReactNode;
  title: string;
  subtitle: string;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className="group flex items-center gap-3 rounded-2xl border border-surface-stroke bg-surface-base p-4 text-left transition-all duration-200 hover:-translate-y-0.5 hover:border-foreground-platinum-green/50 hover:shadow-floating"
    >
      <span className="flex size-11 shrink-0 items-center justify-center rounded-xl bg-surface-base-muted text-foreground-muted transition-all duration-200 group-hover:scale-110 group-hover:bg-foreground-platinum-green/12 group-hover:text-foreground-platinum-green">
        {icon}
      </span>
      <span className="min-w-0 flex-1">
        <span className="block heading-normal text-foreground-default">
          {title}
        </span>
        <span className="body-small block text-foreground-muted">{subtitle}</span>
      </span>
      <ChevronRightIcon className="size-4 shrink-0 text-foreground-more-muted transition-transform duration-200 group-hover:translate-x-0.5 group-hover:text-foreground-platinum-green" />
    </button>
  );
}

// ─── Detail carousel ─────────────────────────────────────────────────────────

export type WalkthroughStep = {
  id: string;
  title: string;
  body: string;
  // The mock-chart region to spotlight on this step (null = whole chart).
  highlight: string | null;
};

// The per-item guided tour: a platinum-tinted header, a mock chart that
// spotlights the current step's region, narration, a Back · dots · Next control,
// and a primary action on the last step. `trailing` hangs persistent call-outs
// (e.g. "what you need") below the tour.
export function WalkthroughCarousel({
  icon,
  title,
  subtitle,
  steps,
  renderMock,
  finalAction,
  trailing,
  initialStepId,
}: {
  icon: ReactNode;
  title: string;
  subtitle: string;
  steps: WalkthroughStep[];
  renderMock: (highlight: string | null) => ReactNode;
  // The last step's primary button — a forward CTA ("Create one") or, for an
  // overview-based how-to, a "Back to overview" action (see WalkthroughModal).
  finalAction: { label: string; onClick: () => void };
  trailing?: ReactNode;
  // The step the tour opens on, for a caller that sends its reader to one
  // step of a topic. Read once, on mount; an id no step has opens the first.
  initialStepId?: string;
}) {
  const { t } = useTranslation();
  const [index, setIndex] = useState(() =>
    Math.max(
      0,
      steps.findIndex((s) => s.id === initialStepId),
    ),
  );
  const step = steps[index];
  const isLast = index === steps.length - 1;

  return (
    <div>
      <WalkthroughDetailHeader icon={icon} title={title} subtitle={subtitle} />

      {/* The mock chart, spotlighting the current step's region. */}
      {renderMock(step.highlight)}

      {/* Narration — re-keyed by step so the copy fades in on each change. */}
      <div key={step.id} className="fade-in mt-3 min-h-[4.5rem]">
        <h4 className="heading-normal text-foreground-default">{step.title}</h4>
        <p className="body-normal mt-1 text-foreground-muted">{step.body}</p>
      </div>

      {/* Step navigation: Back · dots · Next / final action. */}
      <div className="mt-2 flex items-center gap-2">
        {/* Left slot — Back only past the first step (no dead disabled button).
            A neutral pill that mirrors the Next button opposite it — no chevron,
            since Next carries none — so the two step controls read as a pair. */}
        <div className="flex flex-1 justify-start">
          {index > 0 ? (
            <Button
              variant="neutral"
              size="rounded"
              onClick={() => setIndex((i) => Math.max(0, i - 1))}
            >
              {t("Back")}
            </Button>
          ) : null}
        </div>
        <div className="flex items-center gap-1.5">
          {steps.map((s, i) => (
            <button
              key={s.id}
              type="button"
              aria-label={s.title}
              aria-current={i === index ? "step" : undefined}
              onClick={() => setIndex(i)}
              className={`size-2 rounded-full transition-all ${
                i === index
                  ? "w-4 bg-foreground-platinum-green"
                  : "bg-surface-stroke hover:bg-foreground-more-muted"
              }`}
            />
          ))}
        </div>
        {/* Right slot — Next, or the final action on the last step. */}
        <div className="flex flex-1 justify-end">
          {isLast ? (
            <Button
              variant="pro-special"
              size="rounded"
              onClick={finalAction.onClick}
            >
              {finalAction.label}
            </Button>
          ) : (
            <Button
              variant="pro-special"
              size="rounded"
              onClick={() => setIndex((i) => Math.min(steps.length - 1, i + 1))}
            >
              {t("Next")}
            </Button>
          )}
        </div>
      </div>

      {trailing && <div className="mt-5 flex flex-col gap-3">{trailing}</div>}
    </div>
  );
}

// The header shared by the detail carousel and the text fallback: a platinum
// icon tile + the item name and the question it answers.
export function WalkthroughDetailHeader({
  icon,
  title,
  subtitle,
}: {
  icon: ReactNode;
  title: string;
  subtitle: string;
}) {
  return (
    <div className="mb-4 flex items-center gap-2.5">
      <span className="flex size-9 shrink-0 items-center justify-center rounded-xl bg-foreground-platinum-green/12 text-foreground-platinum-green">
        {icon}
      </span>
      <div className="min-w-0">
        <h3 className="heading-section text-foreground-default">{title}</h3>
        <p className="body-small text-foreground-muted">{subtitle}</p>
      </div>
    </div>
  );
}

// A persistent call-out under the tour — "what you need", "if it's not showing".
export function WalkthroughCallout({
  title,
  children,
}: {
  title: string;
  children: ReactNode;
}) {
  return (
    <div className="rounded-xl border border-surface-stroke bg-surface-base-muted/50 p-4">
      <h4 className="body-small font-medium text-foreground-default">{title}</h4>
      <p className="body-small mt-1 text-foreground-muted">{children}</p>
    </div>
  );
}
