'use client';

import Link from 'next/link';
import { useCallback, useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import {
  enrollmentPreview,
  turnOffWorkflow,
  turnOnWorkflow,
} from '@/features/workflows/api.client';
import { workflowRightsOf } from '@/features/permission-sets/api.client';
import { mayUseStepKind, workflowRightsFor } from '@/features/workflows/access';
import type {
  TurnOffMode,
  WorkflowDefinition,
  WorkflowDetail,
  WorkflowEnrollmentPreview,
  WorkflowEnrollmentStatus,
  WorkflowProblem,
  WorkflowStatus,
  WorkflowStep,
  WorkflowSummary,
  WorkflowSchedule,
  WorkflowTrigger,
  EventTriggerBranch,
} from '@/features/workflows/types';
import { eventBranchesOf } from '@/features/workflows/types';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

// ---------------------------------------------------------------------------------------------
// Access
// ---------------------------------------------------------------------------------------------

/**
 * Who may do what (features/workflows/access.ts, as the API): `view_workflows` sees,
 * `manage_workflows` edits; the set's workflow rights narrow that by action (publish, delete,
 * enroll), by kind of step and by object (HUB-746). The CRM admin may do everything. Turning on
 * is per workflow (`canTurnOn` from the API: the admin or the owner). With `objectType`, the
 * answers are for workflows of that object; `forObject` asks about each row of a list.
 */
export function useWorkflowAccess(objectType?: string) {
  const me = useCurrentUser();
  const isAdmin = me.role === 'admin';
  const rules = me.permissionSet.rules;
  const canView =
    isAdmin || Boolean(rules.app.manage_workflows) || Boolean(rules.app.view_workflows);
  const forObject = (type?: string) => workflowRightsFor(rules, isAdmin, type);
  /** May this user add or change a step of this kind: an action's name, 'delay' or 'branch'? */
  const mayUseAction = useCallback(
    (kind: string) => mayUseStepKind(rules, isAdmin, kind),
    [rules, isAdmin],
  );
  return {
    canView,
    ...forObject(objectType),
    forObject,
    mayUseAction,
    /** The objects whose workflows the set may create; null: all of them. */
    editableObjects: isAdmin ? null : workflowRightsOf(rules).objects,
    isAdmin,
    timeZone: me.business.timezone,
  };
}

// ---------------------------------------------------------------------------------------------
// Labels
// ---------------------------------------------------------------------------------------------

export const OBJECT_LABELS: Record<string, { one: string; many: string; path: string }> = {
  contact: { one: 'Contact', many: 'Contacts', path: 'contacts' },
  company: { one: 'Company', many: 'Companies', path: 'companies' },
  deal: { one: 'Deal', many: 'Deals', path: 'deals' },
  lead: { one: 'Lead', many: 'Leads', path: 'leads' },
  ticket: { one: 'Ticket', many: 'Tickets', path: 'tickets' },
  quote: { one: 'Quote', many: 'Quotes', path: 'quotes' },
  call: { one: 'Call', many: 'Calls', path: 'calls' },
};

export function objectLabel(type: string): string {
  return OBJECT_LABELS[type]?.one ?? type;
}

export function recordHref(type: string, id: string): string | null {
  // CL6b: a call's own page.
  if (type === 'call') return `/calls/${id}`;
  const path = OBJECT_LABELS[type]?.path;
  return path ? `/${path}/${id}` : null;
}

/** "Contact 1a2b3c4d" linking to the record page. */
/** A link to a record: its name when known, else the object and the start of its id. */
export function RecordLink({ type, id, name }: { type: string; id: string; name?: string | null }) {
  const href = recordHref(type, id);
  const label = name?.trim() || `${objectLabel(type)} ${id.slice(0, 8)}`;
  return href ? (
    <Link className="rec-link" href={href} title={id}>
      {label}
    </Link>
  ) : (
    <span title={id}>{label}</span>
  );
}

export const EVENT_LABELS: Record<string, string> = {
  'record.created': 'Record is created',
  'record.updated': 'A property changes',
  'association.changed': 'A record is linked or unlinked',
  'deal.stage_changed': 'Deal stage changes',
  'call.logged': 'A call is logged',
  'note.created': 'A note is added',
  'meeting.booked': 'A meeting is booked',
  'meeting.updated': 'A meeting is changed',
  'meeting.cancelled': 'A meeting is cancelled',
  'meeting.outcome_set': 'A meeting outcome is set',
  'email.opened': 'An email is opened',
  'email.clicked': 'An email link is clicked',
  'email.unsubscribed': 'The contact unsubscribes',
  'email.bounced': 'An email bounces',
  'form.submitted': 'A form is submitted',
  // Sequences #88: made on Sequences > Automate.
  'page.viewed': 'A page is viewed',
  'sequence.enrolled': 'Enrolled in a sequence',
  'sequence.finished': 'Finished a sequence',
  'sequence.exited': 'Left a sequence',
  'list.member_added': 'Added to a segment',
  // DL15b: quote workflows.
  'quote.published': 'The quote is published',
  'quote.viewed': 'The buyer views the quote',
  'quote.signed': 'The quote is signed',
  'quote.declined': 'The quote is declined',
  'quote.expired': 'The quote expires',
  'list.member_removed': 'Removed from a segment',
};

export function eventLabel(event: string): string {
  return EVENT_LABELS[event] ?? event;
}

export const ACTION_LABELS: Record<string, string> = {
  set_property: 'Set a property',
  copy_property: 'Copy a property',
  create_record: 'Create a record',
  apply_link_label: 'Apply an association label',
  create_task: 'Create a task',
  internal_email: 'Send an internal email',
  slack_message: 'Send a Slack message',
  send_email: 'Send an email (template)',
  enroll_in_sequence: 'Enroll in a sequence',
  unenroll_from_sequence: 'Unenroll from a sequence',
  in_app_notification: 'Send in-app notification',
  rotate_owner: 'Rotate record to owner',
  add_to_list: 'Add to static list',
  remove_from_list: 'Remove from static list',
  enroll_in_workflow: 'Enroll in another workflow',
  go_to_action: 'Go to action',
  format_data: 'Format data',
  send_webhook: 'Send a webhook',
  google_sheets_row: 'Create Google Sheets row',
  send_sms: 'Send SMS',
  custom_code: 'Custom code',
};

export function actionLabel(action: string): string {
  return ACTION_LABELS[action] ?? action;
}

const STATUS_LABELS: Record<WorkflowStatus, string> = { draft: 'Draft', on: 'On', off: 'Off' };

export function WorkflowStatusBadge({ status }: { status: WorkflowStatus }) {
  return (
    <span
      className={cn(
        'badge',
        status === 'on' && 'badge--success',
        status === 'draft' && 'badge--warning',
      )}
    >
      {STATUS_LABELS[status] ?? status}
    </span>
  );
}

const ENROLLMENT_STATUS_LABELS: Record<WorkflowEnrollmentStatus, string> = {
  running: 'Running',
  waiting: 'Waiting',
  completed: 'Completed',
  failed: 'Failed',
  cancelled: 'Left',
};

export function EnrollmentStatusBadge({ status }: { status: WorkflowEnrollmentStatus }) {
  return (
    <span
      className={cn(
        'badge',
        status === 'completed' && 'badge--success',
        status === 'failed' && 'badge--danger',
        (status === 'running' || status === 'waiting') && 'badge--info',
      )}
    >
      {ENROLLMENT_STATUS_LABELS[status] ?? status}
    </span>
  );
}

export const END_REASON_LABELS: Record<string, string> = {
  completed: 'Reached the end',
  unenrolled: 'Taken out by hand',
  no_longer_matching: 'No longer matches the trigger',
  workflow_turned_off: 'Workflow turned off',
  record_deleted: 'Record deleted',
  failed: 'A step failed',
  loop_guard: 'Stopped by the loop guard',
};

export const SOURCE_LABELS: Record<string, string> = {
  event: 'Trigger event',
  filter: 'Matched the filter',
  manual: 'By hand',
  existing: 'Existing record (turned on)',
};

/** A date and time in the business time zone, e.g. "Oct 3, 2026, 14:05". */
export function formatWhen(iso: string | null | undefined, timeZone?: string): string {
  if (!iso) return '—';
  const date = new Date(iso);
  if (Number.isNaN(date.getTime())) return iso;
  try {
    return date.toLocaleString(undefined, {
      timeZone,
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  } catch {
    return date.toLocaleString();
  }
}

// ---------------------------------------------------------------------------------------------
// Definitions
// ---------------------------------------------------------------------------------------------

export function emptyDefinition(): WorkflowDefinition {
  return {
    formatVersion: 1,
    trigger: { type: 'manual' },
    settings: { reEnrollment: { enabled: false, on: [] }, unenrollWhenNoLongerMatching: false },
    steps: [],
  };
}

/** A stored definition with the defaults filled in (settings, steps). */
export function normalizeDefinition(raw: Record<string, unknown> | null | undefined) {
  if (!raw) return emptyDefinition();
  const base = emptyDefinition();
  const settings = (raw.settings ?? {}) as Partial<WorkflowDefinition['settings']>;
  return {
    ...raw,
    formatVersion: 1,
    trigger: (raw.trigger as WorkflowTrigger | undefined) ?? base.trigger,
    settings: {
      ...settings,
      reEnrollment: {
        enabled: Boolean(settings.reEnrollment?.enabled),
        on: settings.reEnrollment?.on ?? [],
      },
      unenrollWhenNoLongerMatching: Boolean(settings.unenrollWhenNoLongerMatching),
    },
    steps: Array.isArray(raw.steps) ? (raw.steps as WorkflowStep[]) : [],
  } as WorkflowDefinition;
}

/** The definition being worked on: the draft when there is one, else the published one. */
export function workingDefinition(workflow: WorkflowDetail): WorkflowDefinition {
  return normalizeDefinition(workflow.draft?.definition ?? workflow.definition);
}

function conditionCount(filter: unknown): number {
  const groups = (filter as { groups?: { conditions?: unknown[] }[] } | undefined)?.groups ?? [];
  return groups.reduce((n, g) => n + (g.conditions?.length ?? 0), 0);
}

/** "08:00" -> "8:00 AM" (a schedule trigger's time, in the business time zone). */
export function clockLabel(time: string): string {
  const [h = 0, m = 0] = time.split(':').map(Number);
  return `${h % 12 || 12}:${String(m).padStart(2, '0')} ${h < 12 ? 'AM' : 'PM'}`;
}

const WEEKDAY_SHORT: Record<string, string> = {
  mon: 'Mon',
  tue: 'Tue',
  wed: 'Wed',
  thu: 'Thu',
  fri: 'Fri',
  sat: 'Sat',
  sun: 'Sun',
};

/** A-03: "Daily at 8:00 AM", "Weekly on Mon, Fri at 9:30 AM", "7 days before closeDate at …". */
export function scheduleSummary(schedule: WorkflowSchedule, propertyLabel?: string): string {
  const at = `at ${clockLabel(schedule.time)}`;
  if (schedule.frequency === 'daily') return `Daily ${at}`;
  if (schedule.frequency === 'weekly') {
    return `Weekly on ${schedule.days.map((d) => WEEKDAY_SHORT[d] ?? d).join(', ')} ${at}`;
  }
  if (schedule.frequency === 'monthly') return `Monthly on day ${schedule.dayOfMonth} ${at}`;
  // Without its label, the field name in words: "custom.renewal_date" -> "renewal date".
  const field =
    propertyLabel ??
    schedule.property
      .replace(/^custom\./, '')
      .replace(/([a-z])At$/, '$1')
      .replace(/([a-z])([A-Z])/g, '$1 $2')
      .replace(/_/g, ' ')
      .toLowerCase();
  const n = schedule.offsetDays;
  const when =
    n === 0
      ? `On ${field}`
      : `${Math.abs(n)} day${Math.abs(n) === 1 ? '' : 's'} ${n < 0 ? 'before' : 'after'} ${field}`;
  return `${when} ${at}`;
}

export function triggerSummary(trigger: WorkflowTrigger): string {
  if (trigger.type === 'manual') return 'Enrolled by hand only';
  if (trigger.type === 'filter') {
    const n = conditionCount(trigger.filter);
    const groups = trigger.filter.groups.filter((g) => g.conditions.length > 0).length;
    const count = `${n} condition${n === 1 ? '' : 's'}`;
    // A-04: OR groups are named, as on the card.
    return groups > 1
      ? `When a record matches any of ${groups} groups (${count})`
      : `When a record matches the filter (${count})`;
  }
  if (trigger.type === 'schedule' || trigger.type === 'webhook') {
    const text =
      trigger.type === 'schedule'
        ? scheduleSummary(trigger.schedule)
        : 'When a webhook is received';
    const n = conditionCount(trigger.filter);
    return n ? `${text} (and ${n} condition${n === 1 ? '' : 's'})` : text;
  }
  // A-04: OR'd events, then the refine conditions.
  const text = eventBranchesOf(trigger).map(eventBranchSummary).join(' or ');
  const r = conditionCount(trigger.refine);
  return r ? `${text}, if they meet ${r} condition${r === 1 ? '' : 's'}` : text;
}

/** One event of an event trigger: "Deal stage changes (and 2 conditions)". */
export function eventBranchSummary(branch: EventTriggerBranch): string {
  let text = eventLabel(branch.event);
  if (branch.event === 'record.updated' && branch.property) {
    text = `${branch.property} changes`;
  }
  if (branch.event === 'association.changed') {
    const what = branch.linkedObject ? (OBJECT_LABELS[branch.linkedObject]?.one ?? '') : 'A record';
    const how =
      branch.linkAction === 'linked'
        ? 'is linked'
        : branch.linkAction === 'unlinked'
          ? 'is unlinked'
          : 'is linked or unlinked';
    text = `${what || 'A record'} ${how}`;
  }
  const n = conditionCount(branch.filter);
  return n ? `${text} (and ${n} condition${n === 1 ? '' : 's'})` : text;
}

/** "1 day", "2 days", "1 business day". */
function amountText(amount: number, unit: string, business = false): string {
  const word = amount === 1 ? unit.replace(/s$/, '') : unit;
  return `${amount} ${business && unit === 'days' ? 'business ' : ''}${word}`;
}

/** Without its label, a field name in words: "custom.renewal_date" -> "Renewal date". */
function fieldWords(key: string): string {
  const words = key
    .replace(/^custom\./, '')
    .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
    .replace(/_/g, ' ')
    .toLowerCase();
  return words.charAt(0).toUpperCase() + words.slice(1);
}

export function delaySummary(
  step: Extract<WorkflowStep, { type: 'delay' }>,
  labelOf?: (key: string) => string | undefined,
): string {
  const d = step.delay;
  if (d.kind === 'duration') {
    return `Wait ${amountText(d.amount, d.unit, d.businessDays)}`;
  }
  if (d.kind === 'until_event') {
    return `Wait until: ${eventLabel(d.event)} (at most ${amountText(d.expiresAfter.amount, d.expiresAfter.unit)})`;
  }
  // Go-live 949: "Wait until Close date", "Wait until 2 days before Close date at 9:00 AM".
  const offset = d.offsetDays ?? 0;
  const rel =
    offset === 0
      ? ''
      : `${amountText(Math.abs(offset), 'days')} ${offset > 0 ? 'after' : 'before'} `;
  const field = d.field
    ? (labelOf?.(d.field) ?? fieldWords(d.field))
    : 'a date (choose a date property)';
  return `Wait until ${rel}${field}${d.time ? ` at ${clockLabel(d.time)}` : ''}`;
}

/** 100 shared out over `n` random-split paths: 50/50, 34/33/33 (the API takes whole percents). */
export function evenSplit(n: number): number[] {
  return Array.from({ length: n }, (_, i) => Math.floor(100 / n) + (i < 100 % n ? 1 : 0));
}

/** What a branch path is chosen by: "Path 1 (= Won)", "Path A (50%)", or just its name. */
export function branchPathText(
  step: Extract<WorkflowStep, { type: 'branch' }>,
  path: Extract<WorkflowStep, { type: 'branch' }>['paths'][number],
): string {
  if (step.branchType === 'value_equals') return `${path.label} (= ${path.value ?? ''})`;
  if (step.branchType === 'random_split') return `${path.label} (${path.percent ?? 0}%)`;
  return path.label;
}

/**
 * Go-live 951: a text with merge fields as a person reads it in a summary:
 * "Call {{contact.firstName | the new lead}}" -> "Call the new lead", and without a fallback
 * "Review {{deal.name}}" -> "Review [Deal name]". The step's own settings keep the fields.
 */
export function readableMerge(text: string): string {
  return text.replace(
    /\{\{\s*([^{}|]+?)\s*(?:\|\s*([^{}]*?)\s*)?\}\}/g,
    (_raw, path: string, fallback: string | undefined) =>
      fallback || `[${fieldWords(path.replace(/\./g, ' '))}]`,
  );
}

/** `labelOf` names a written property (HUB-258); without it the title shows the field key. */
export function stepTitle(
  step: WorkflowStep,
  labelOf?: (key: string) => string | undefined,
): string {
  if (step.type === 'delay') return delaySummary(step, labelOf);
  if (step.type === 'branch') {
    // HUB-277: the design's "Random 50/50 split" (workflow-editor.js:333), with the paths' shares.
    if (step.branchType === 'random_split') {
      return `Random ${step.paths.map((p) => p.percent ?? 0).join('/')} split`;
    }
    return step.branchType === 'if_then'
      ? `If/then branch (${step.paths.length} path${step.paths.length === 1 ? '' : 's'})`
      : `Branch on ${step.property || '(property)'}`;
  }
  const c = step.config as Record<string, unknown>;
  if (step.action === 'create_task' && typeof c.title === 'string' && c.title) {
    return `Create task: ${readableMerge(c.title)}`;
  }
  if (step.action === 'set_property' && typeof c.property === 'string' && c.property) {
    return `Set ${labelOf?.(c.property) ?? c.property}`;
  }
  if (step.action === 'internal_email' && typeof c.subject === 'string' && c.subject) {
    return `Internal email: ${readableMerge(c.subject)}`;
  }
  if (step.action === 'in_app_notification' && typeof c.title === 'string' && c.title) {
    return `In-app notification: ${readableMerge(c.title)}`;
  }
  if (step.action === 'format_data' && typeof c.source === 'string' && c.source) {
    return `Format ${c.source}`;
  }
  if (step.action === 'send_webhook' && typeof c.url === 'string' && c.url) {
    return `Webhook: ${typeof c.method === 'string' ? c.method : 'POST'} ${c.url}`;
  }
  return actionLabel(step.action);
}

/** Every step of a definition, with nested branch steps, by id. */
export function stepsById(steps: WorkflowStep[]): Map<string, WorkflowStep> {
  const map = new Map<string, WorkflowStep>();
  const walk = (list: WorkflowStep[]) => {
    for (const step of list) {
      map.set(step.id, step);
      if (step.type === 'branch') {
        step.paths.forEach((p) => walk(p.steps ?? []));
        walk(step.otherwise?.steps ?? []);
      }
    }
  };
  walk(steps);
  return map;
}

// ---------------------------------------------------------------------------------------------
// Problems (validate / publish / turn on)
// ---------------------------------------------------------------------------------------------

/** The `{ field, message }` list of a 400 (publish / turn-on problems). */
export function problemsFromError(err: unknown): WorkflowProblem[] | null {
  if (!isApiError(err) || err.status !== 400 || !err.details?.length) return null;
  const problems = err.details.flatMap((d) => {
    if (typeof d !== 'object' || d === null) return [];
    const { field, path, message } = d as Record<string, unknown>;
    const at = typeof field === 'string' ? field : typeof path === 'string' ? path : '';
    if (typeof message !== 'string') return [];
    return [{ path: at, message }];
  });
  return problems.length ? problems : null;
}

/** "steps[2].paths[0].steps[1].config.title" -> "Step 3 › path 1 › step 2 · config.title". */
export function problemLabel(path: string): string {
  if (!path) return 'Workflow';
  const parts: string[] = [];
  let rest = path;
  const re = /^(steps|paths|otherwise\.steps)\[(\d+)\]\.?/;
  let match = re.exec(rest);
  while (match) {
    const n = Number(match[2]) + 1;
    parts.push(match[1] === 'paths' ? `path ${n}` : `step ${n}`);
    rest = rest.slice(match[0].length);
    if (rest.startsWith('otherwise.')) {
      parts.push('otherwise');
      rest = rest.slice('otherwise.'.length);
    }
    match = re.exec(rest);
  }
  if (!parts.length) return path;
  const head = parts.join(' › ');
  const label = head.charAt(0).toUpperCase() + head.slice(1);
  return rest ? `${label} · ${rest}` : label;
}

/** Field names in problem paths, as words ("userIds" would otherwise read "user ids"). */
const PROBLEM_NOUNS: Record<string, string> = {
  to: 'recipient',
  userIds: 'user',
  conditions: 'condition',
  groups: 'condition group',
  paths: 'path',
  steps: 'action',
  body: 'message',
  stepId: 'action to go to',
  workflowId: 'workflow',
  templateId: 'email template',
  sequenceId: 'sequence',
  listId: 'segment',
  listIds: 'segment',
  url: 'URL',
};

/** "Path 1", "Step 2 › path 1", "Trigger", "Settings": where in the workflow a problem is. */
function problemPlace(path: string): { place: string; rest: string } {
  const label = problemLabel(path);
  const [head, rest = ''] = label.split(' · ');
  if (head !== label || /^(Step|Path)/.test(head ?? '')) return { place: head ?? '', rest };
  const [first = '', ...more] = path.split('.');
  const place = first === 'trigger' ? 'Trigger' : first === 'settings' ? 'Settings' : 'Workflow';
  return { place, rest: first === 'trigger' || first === 'settings' ? more.join('.') : path };
}

/**
 * A-06: a problem from validate / publish / turn on in words, for people: "Path 1: add at least
 * one condition" instead of "steps[0].paths[0] · condition.groups.0.conditions: Too small:
 * expected array to have >=1 items". Messages the API already words stay as they are.
 */
export function problemText(problem: WorkflowProblem): string {
  const { place, rest } = problemPlace(problem.path);
  const key = rest
    .split('.')
    .filter((part) => part && !/^\d+$/.test(part))
    .at(-1);
  const noun = key
    ? (PROBLEM_NOUNS[key] ?? key.replace(/([a-z])([A-Z])/g, '$1 $2').toLowerCase())
    : 'value';
  const message = problem.message.trim();
  let what: string;
  if (/^(too small: expected array|array must contain at least 1)/i.test(message)) {
    what = `add at least one ${noun}`;
  } else if (
    /^required$/i.test(message) ||
    /received undefined$/i.test(message) ||
    /^(too small: expected string|string must contain at least 1)/i.test(message)
  ) {
    what = `fill in the ${noun}`;
  } else if (/^(invalid|too (big|small)|expected)/i.test(message) && key) {
    what = `check the ${noun}: ${message.charAt(0).toLowerCase()}${message.slice(1)}`;
  } else {
    what = message;
  }
  return `${place}: ${what}`;
}

export function ProblemsList({ problems }: { problems: WorkflowProblem[] }) {
  return (
    <ul className="crm-mb-0 crm-ps-3">
      {problems.map((problem, i) => (
        <li key={`${problem.path}-${i}`}>{problemText(problem)}</li>
      ))}
    </ul>
  );
}

// ---------------------------------------------------------------------------------------------
// Turn on / off
// ---------------------------------------------------------------------------------------------

/**
 * Turn on: shows who `enrollExisting` would enroll (GET enrollment-preview), then POST turn-on.
 * Problems in the published version (400) are listed in place.
 */
export function TurnOnDialog({
  workflow,
  onClose,
  onDone,
}: {
  workflow: WorkflowSummary | null;
  onClose: () => void;
  onDone: (updated: WorkflowDetail) => void;
}) {
  const [preview, setPreview] = useState<WorkflowEnrollmentPreview | null>(null);
  const [previewError, setPreviewError] = useState<string | null>(null);
  const [enrollExisting, setEnrollExisting] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [problems, setProblems] = useState<WorkflowProblem[]>([]);
  const { timeZone, canEnroll } = useWorkflowAccess(workflow?.objectType);

  const id = workflow?.id;
  useEffect(() => {
    setPreview(null);
    setPreviewError(null);
    setEnrollExisting(false);
    setError(null);
    setProblems([]);
    if (!id) return;
    let cancelled = false;
    enrollmentPreview(id).then(
      (res) => {
        if (!cancelled) setPreview(res);
      },
      (err) => {
        if (!cancelled) setPreviewError(errorText(err));
      },
    );
    return () => {
      cancelled = true;
    };
  }, [id]);

  const confirm = async () => {
    if (!workflow || busy) return;
    setBusy(true);
    setError(null);
    setProblems([]);
    try {
      const updated = await turnOnWorkflow(workflow.id, {
        enrollExisting,
        updatedAt: workflow.updatedAt,
      });
      onDone(updated);
    } catch (err) {
      const found = problemsFromError(err);
      if (found) setProblems(found);
      setError(
        isApiError(err) && err.isConflict
          ? `${errorText(err)}. Reload the page and try again.`
          : errorText(err),
      );
    } finally {
      setBusy(false);
    }
  };

  const close = busy ? () => {} : onClose;
  const noExisting = preview?.trigger === 'manual';

  return (
    <CrmModal id="wfTurnOnModal" open={Boolean(workflow)} onClose={close}>
      <ModalHeader id="wfTurnOnModal" title="Turn workflow on?" onClose={close} />
      <div className="modal__body">
        <p className="crm-mb-3">
          <strong>{workflow?.name}</strong> runs version {workflow?.currentVersionNo ?? '—'}.
          {workflow?.hasDraft
            ? ' Unpublished draft changes are not used until you publish them.'
            : ''}
        </p>
        {previewError ? <Alert tone="warning">{previewError}</Alert> : null}
        {!preview && !previewError ? (
          <p className="crm-text-muted crm-fs-7">Checking which records match now…</p>
        ) : null}
        {preview && !noExisting && canEnroll ? (
          <label className="check-row" htmlFor="wfEnrollExisting">
            <input
              id="wfEnrollExisting"
              type="checkbox"
              checked={enrollExisting}
              onChange={(e) => setEnrollExisting(e.target.checked)}
            />
            <span>
              Also enroll existing records:{' '}
              <strong>
                {preview.count} record{preview.count === 1 ? '' : 's'}
              </strong>{' '}
              {preview.trigger === 'filter'
                ? 'match the trigger now'
                : `had the trigger event while it was off${
                    preview.since ? ` (since ${formatWhen(preview.since, timeZone)})` : ''
                  }`}
              .
            </span>
          </label>
        ) : null}
        {preview && noExisting ? (
          <p className="crm-text-muted crm-fs-7">
            This workflow has a manual trigger: records are only enrolled by hand.
          </p>
        ) : null}
        {preview && !noExisting && !enrollExisting ? (
          <p className="crm-text-muted crm-fs-8 crm-mt-2 crm-mb-0">
            Without this, only records that match or have the event from now on are enrolled.
          </p>
        ) : null}
        {error ? (
          <div className="crm-mt-3">
            <Alert tone="danger">
              {error}
              {problems.length ? <ProblemsList problems={problems} /> : null}
            </Alert>
          </div>
        ) : null}
      </div>
      <div className="modal__footer">
        <button type="button" className="btn-crm btn-crm--outline" onClick={close} disabled={busy}>
          Cancel
        </button>
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
          onClick={() => void confirm()}
          disabled={busy}
          aria-busy={busy}
        >
          Turn on
        </button>
      </div>
    </CrmModal>
  );
}

export const REMOVE_NOT_ALLOWED =
  'Take every record out now (your permission set does not allow unenrolling)';

/** Turn off: everyone leaves now (`remove_all`), or they finish (`let_finish`). */
export function TurnOffDialog({
  workflow,
  onClose,
  onDone,
}: {
  workflow: WorkflowSummary | null;
  onClose: () => void;
  onDone: (removed: number) => void;
}) {
  const { canEnroll } = useWorkflowAccess(workflow?.objectType);
  const [mode, setMode] = useState<TurnOffMode>('let_finish');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    setMode('let_finish');
    setError(null);
  }, [workflow?.id]);

  const confirm = async () => {
    if (!workflow || busy) return;
    setBusy(true);
    setError(null);
    try {
      const res = await turnOffWorkflow(workflow.id, { mode, updatedAt: workflow.updatedAt });
      onDone(res.removed);
    } catch (err) {
      setError(
        isApiError(err) && err.isConflict
          ? `${errorText(err)}. Reload the page and try again.`
          : errorText(err),
      );
    } finally {
      setBusy(false);
    }
  };

  const close = busy ? () => {} : onClose;
  const n = workflow?.enrolledCount ?? 0;

  return (
    <CrmModal id="wfTurnOffModal" open={Boolean(workflow)} onClose={close}>
      <ModalHeader id="wfTurnOffModal" title="Turn workflow off?" onClose={close} />
      <div className="modal__body">
        <p className="crm-mb-3">
          No new records enter <strong>{workflow?.name}</strong> while it is off.{' '}
          {n > 0
            ? `${n} record${n === 1 ? ' is' : 's are'} in it now.`
            : 'No records are in it now.'}
        </p>
        <div className="crm-d-flex crm-flex-column crm-gap-2">
          <label className="check-row" htmlFor="wfOffLetFinish">
            <input
              id="wfOffLetFinish"
              type="radio"
              name="wfTurnOffMode"
              checked={mode === 'let_finish'}
              onChange={() => setMode('let_finish')}
            />
            <span>Let records in it finish their remaining steps</span>
          </label>
          <label className="check-row" htmlFor="wfOffRemoveAll">
            <input
              id="wfOffRemoveAll"
              type="radio"
              name="wfTurnOffMode"
              checked={mode === 'remove_all'}
              disabled={!canEnroll}
              onChange={() => setMode('remove_all')}
            />
            <span>{canEnroll ? 'Take every record out now' : REMOVE_NOT_ALLOWED}</span>
          </label>
        </div>
        {error ? (
          <div className="crm-mt-3">
            <Alert tone="danger">{error}</Alert>
          </div>
        ) : null}
      </div>
      <div className="modal__footer">
        <button type="button" className="btn-crm btn-crm--outline" onClick={close} disabled={busy}>
          Cancel
        </button>
        <button
          type="button"
          className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
          onClick={() => void confirm()}
          disabled={busy}
          aria-busy={busy}
        >
          Turn off
        </button>
      </div>
    </CrmModal>
  );
}

/** "Your permissions do not allow …" page body. */
export function NoWorkflowAccess({ title = 'Workflows' }: { title?: string }) {
  return (
    <div className="companies-page">
      <div className="page-header">
        <div className="page-title">
          <h1>{title}</h1>
        </div>
      </div>
      <Alert tone="warning">
        Your permissions do not allow seeing workflows. Ask a CRM admin for the &ldquo;View
        workflows&rdquo; permission.
      </Alert>
    </div>
  );
}
