'use client';

import { cn } from '@/lib/utils/cn';
import type { Pipeline, PipelineStage } from '@/features/deals/types';

export const FORWARD_ONLY_TITLE = 'Deals only move forward in this pipeline';

export type StageBarStep = {
  stage: PipelineStage;
  /** The deal's stage. */
  active: boolean;
  /** An open stage before the deal's (passed on the way). */
  done: boolean;
  /** Why it can't be chosen; null when it can. */
  blocked: string | null;
};

/**
 * QA #366: the steps of the deal stage bar: the pipeline's live stages in order, the deal's
 * stage active, the open stages before it done. A stage can be chosen only as the stage API
 * allows it (POST /deals/:id/stage): with edit rights on the stage, and, in a forward-only
 * pipeline without the restore permission, only a later stage.
 */
export function stageBarSteps(
  pipeline: Pipeline,
  currentStageId: string,
  opts: { lockedTitle: string | null; canMoveBack: boolean },
): StageBarStep[] {
  const current = pipeline.stages.find((s) => s.id === currentStageId);
  const stages = pipeline.stages
    .filter((s) => !s.archived)
    .sort((a, b) => a.displayOrder - b.displayOrder);
  return stages.map((stage) => {
    const active = stage.id === currentStageId;
    const before = current ? stage.displayOrder < current.displayOrder : false;
    return {
      stage,
      active,
      done: before && stage.stageType === 'open',
      blocked: active
        ? null
        : (opts.lockedTitle ??
          (!opts.canMoveBack && current && stage.displayOrder <= current.displayOrder
            ? FORWARD_ONLY_TITLE
            : null)),
    };
  });
}

/** The design's deal stage bar (record.php `.rp-stages`, record-page.js "deal stage bar"). */
export function DealStageBar({
  steps,
  busy,
  onSelect,
}: {
  steps: StageBarStep[];
  /** A move is being saved. */
  busy: boolean;
  onSelect: (stage: PipelineStage) => void;
}) {
  if (!steps.length) return null;
  return (
    <nav className="rp-stages" aria-label="Deal stage" aria-busy={busy || undefined}>
      {steps.map(({ stage, active, done, blocked }) => (
        <button
          key={stage.id}
          type="button"
          className={cn('rp-stage', active && 'is-active', done && 'is-done')}
          aria-pressed={active}
          aria-disabled={blocked || busy ? true : undefined}
          title={blocked ?? (active ? undefined : `Move to ${stage.name}`)}
          onClick={() => {
            if (active || blocked || busy) return;
            onSelect(stage);
          }}
        >
          {stage.name}
        </button>
      ))}
    </nav>
  );
}
