'use client';

import Link from 'next/link';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { useConfirm } from '@/components/crm/useConfirm';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { addListMembers, createList } from '@/features/lists/api.client';
import { todayIn } from '@/features/reports/format';
import {
  bulkControlSequenceEnrollments,
  controlSequenceEnrollment,
  getSequenceEnrollment,
  listSequenceEnrollments,
  sequenceEnrollmentBreakdown,
} from '@/features/sequences/api.client';
import type {
  EnrollmentBreakdown,
  EnrollmentBucket,
  EnrollmentReason,
  ListEnrollmentsParams,
  SequenceControlAction,
  SequenceEnrollment,
  SequenceStepFixAction,
} from '@/features/sequences/types';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { plural } from '@/lib/utils/plural';
import { Kebab } from './DynamicSequenceCanvas';
import { useSenderZone } from './EnrollReview';
import {
  DateRangeFilter,
  EnrolledByFilter,
  Pager,
  ValuesFilter,
  type DateRange,
} from './SequencesAnalyzeTab';

type Bucket = 'all' | EnrollmentBucket;

const BUCKETS: Array<{ key: Bucket; label: string }> = [
  { key: 'all', label: 'All enrollments' },
  { key: 'scheduled', label: 'Scheduled' },
  { key: 'in_progress', label: 'In progress' },
  { key: 'paused', label: 'Paused' },
  { key: 'finished', label: 'Finished' },
  { key: 'error', label: 'Error' },
];

/** HubSpot's fixed sub-statuses, listed even at 0 (Paused also has our mailbox pause). */
const SUBS: Partial<Record<EnrollmentBucket, Array<{ key: EnrollmentReason; label: string }>>> = {
  paused: [
    { key: 'paused_user', label: 'By user' },
    { key: 'paused_task', label: 'By task' },
    { key: 'paused_mailbox', label: 'Mailbox disconnected' },
  ],
  finished: [
    { key: 'finished_manual', label: 'Manual' },
    { key: 'finished_replied', label: 'Replied' },
    { key: 'finished_workflow', label: 'Workflow' },
    { key: 'finished_meeting', label: 'Meeting' },
    { key: 'finished_no_response', label: 'No response' },
  ],
  error: [
    { key: 'error_send_limit', label: 'Send limit' },
    { key: 'error_bounced', label: 'Bounced' },
    { key: 'error_unsubscribed', label: 'Unsubscribed' },
    { key: 'error_attachment', label: 'Attachment too large' },
    { key: 'error_automation', label: 'Automation error' },
    { key: 'error_inbox', label: 'Inbox disconnected' },
    { key: 'error_downgrade', label: 'User downgrade' },
    { key: 'error_other', label: 'Other' },
  ],
};

/** Rows per page (HubSpot: "25 per page"); the bulk actions take at most 100 at once. */
const PER_PAGE_OPTIONS = [25, 50, 100] as const;
/** Contacts read for "Create segment" (newest first). */
const SEGMENT_PAGE = 100;
const SEGMENT_MAX_PAGES = 20;

const EXIT_LABELS: Record<string, string> = {
  finished: 'No response',
  replied: 'Replied',
  meeting_booked: 'Meeting',
  bounced: 'Bounced',
  unsubscribed: 'Unsubscribed',
  unenrolled: 'Manual',
  contact_deleted: 'Contact deleted',
  no_email: 'No email',
  step_failed: 'Automation error',
  // SEQ-R-B7: "Unenroll all contacts at the company".
  colleague_replied: 'Colleague replied',
  colleague_meeting_booked: 'Colleague booked a meeting',
  // Sequences: the sequence was deleted (its open enrollments exit).
  sequence_deleted: 'Sequence deleted',
};
const PAUSE_LABELS: Record<string, string> = {
  manual: 'By user',
  task: 'By task',
  mailbox_disconnected: 'Mailbox disconnected',
};

/** Ended by the contact's address: HubSpot lists these under Error (as the API's buckets do). */
const ADDRESS_EXITS = new Set(['bounced', 'unsubscribed']);

function bucketOf(row: SequenceEnrollment): EnrollmentBucket {
  // A first step whose task is open has run: the contact is in progress (QA 16 Oct #138).
  if (row.status === 'active') {
    return row.currentStep <= 0 && !row.waitingOnTask ? 'scheduled' : 'in_progress';
  }
  if (row.status === 'paused') return 'paused';
  if (row.status === 'failed') return 'error';
  return ADDRESS_EXITS.has(row.exitReason ?? '') ? 'error' : 'finished';
}

const STATUS_TEXT: Record<EnrollmentBucket, string> = {
  scheduled: 'Scheduled',
  in_progress: 'In progress',
  paused: 'Paused',
  finished: 'Finished',
  error: 'Error',
};

/** A contact a person unenrolled stopped part way: not "Finished" (QA 16 Oct #136). */
const statusText = (row: SequenceEnrollment) =>
  row.status === 'exited' && row.exitReason === 'unenrolled'
    ? 'Unenrolled'
    : row.waitingOnTask
      ? 'Waiting on task'
      : STATUS_TEXT[bucketOf(row)];

/** The sub-reason of a status (HubSpot's expandable statuses, QA 16 Oct #114). */
function reasonOf(row: SequenceEnrollment): string | null {
  const b = bucketOf(row);
  if (b === 'finished') return EXIT_LABELS[row.exitReason ?? ''] ?? null;
  if (b === 'paused') return PAUSE_LABELS[row.pauseReason ?? ''] ?? null;
  if (b === 'error') return EXIT_LABELS[row.exitReason ?? ''] ?? EXIT_LABELS.step_failed!;
  return null;
}

/** A date in your profile time zone (else the business's), as the Scheduled tab shows them. */
function day(iso: string | null, timeZone: string): string {
  if (!iso) return '-';
  const d = new Date(iso);
  return Number.isNaN(d.getTime())
    ? '-'
    : d.toLocaleDateString(undefined, {
        month: 'short',
        day: 'numeric',
        year: 'numeric',
        timeZone,
      });
}

/** Whole days from `from` to the local day of `iso` (both YYYY-MM-DD in `timeZone`). */
function daysUntil(iso: string, from: string, timeZone: string): number {
  const local = new Date(iso).toLocaleDateString('en-CA', { timeZone });
  return Math.round((Date.parse(local) - Date.parse(from)) / 86_400_000);
}

const STEP_TYPE_TEXT: Record<string, string> = {
  automated_email: 'Automated email',
  manual_email: 'Manual email',
  call_task: 'Call',
  task: 'Task',
};

/** Enrollments tab of one sequence (HubSpot: status list, filters, table, 25 per page). */
export function SequenceEnrollmentsTab({
  sequenceId,
  enrolledByName,
  reloadKey,
  onChanged,
}: {
  sequenceId: string;
  enrolledByName: (userId: string) => string;
  /** Changes when contacts were enrolled elsewhere on the page. */
  reloadKey: number;
  /** An enrollment was paused, resumed or unenrolled here (the page's counts change). */
  onChanged?: () => void;
}) {
  const toast = useToast();
  const me = useCurrentUser();
  const { confirm, dialog: confirmDialog } = useConfirm();
  // Sequences QA BUG-02: dates and the Enrollment date filter's days in one zone, the profile's
  // else the business's (the API reads the filter's days in it too), as the Scheduled tab.
  const timeZone = useSenderZone();
  const today = todayIn(timeZone);
  const [rows, setRows] = useState<SequenceEnrollment[] | null>(null);
  const [total, setTotal] = useState(0);
  const [breakdown, setBreakdown] = useState<EnrollmentBreakdown | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [bucket, setBucket] = useState<Bucket>('all');
  /** A sub-status of the bucket (e.g. Finished › Replied); '' for all of it. */
  const [reason, setReason] = useState<EnrollmentReason | ''>('');
  const [search, setSearch] = useState('');
  /** The search sent to the API (typing settles first). */
  const [query, setQuery] = useState('');
  /** Only the newest load may set the rows (an older, slower one is dropped). */
  const loadSeq = useRef(0);
  const [companyIds, setCompanyIds] = useState<string[]>([]);
  // HubSpot starts on your own enrollments, with no date range (EDT-34).
  const [enrolledBy, setEnrolledBy] = useState<string[]>([me.user.id]);
  const [range, setRange] = useState<DateRange | null>(null);
  const [perPage, setPerPage] = useState<number>(PER_PAGE_OPTIONS[0]);
  const [pageState, setPageState] = useState({ page: 1, key: '' });
  const [busyId, setBusyId] = useState<string | null>(null);
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [bulkBusy, setBulkBusy] = useState(false);
  const [segmentOpen, setSegmentOpen] = useState(false);
  const [segmentIds, setSegmentIds] = useState<string[]>([]);
  const [segmentBusy, setSegmentBusy] = useState(false);

  useEffect(() => {
    const timer = window.setTimeout(() => setQuery(search.trim()), 300);
    return () => window.clearTimeout(timer);
  }, [search]);

  /** The filters the list and its counts share (the API reads the days in your zone). */
  const filters: Omit<ListEnrollmentsParams, 'bucket' | 'reason' | 'page' | 'limit'> = {
    ...(query && { search: query }),
    ...(companyIds.length > 0 && { companyId: companyIds.join(',') }),
    ...(enrolledBy.length > 0 && { enrolledBy: enrolledBy.join(',') }),
    ...(range && { enrolledFrom: range.from, enrolledTo: range.to }),
  };
  const filterKey = JSON.stringify([filters, bucket, reason, perPage]);
  const page = pageState.key === filterKey ? pageState.page : 1;

  const load = useCallback(async () => {
    const seq = ++loadSeq.current;
    setError(null);
    try {
      const [list, counts] = await Promise.all([
        listSequenceEnrollments(sequenceId, {
          ...filters,
          ...(bucket !== 'all' && { bucket }),
          ...(reason && { reason }),
          limit: perPage,
          page,
        }),
        sequenceEnrollmentBreakdown(sequenceId, filters),
      ]);
      if (seq !== loadSeq.current) return;
      setRows(list.data);
      setTotal(list.total ?? list.data.length);
      setBreakdown(counts);
      setSelected(new Set());
    } catch (err) {
      if (seq !== loadSeq.current) return;
      setError(errorText(err));
      setRows([]);
    }
    // `filters` is built from the values in `filterKey`.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sequenceId, filterKey, page]);

  useEffect(() => {
    void load();
  }, [load, reloadKey]);

  // Numbered in the enrollment's own version: contacts keep the steps they started with, so
  // the sequence's current steps can't number them (QA 16 Oct #144).
  const stepText = (row: SequenceEnrollment) => {
    const total = Math.max(row.stepCount ?? 0, 1);
    if (row.stepNumber === null || row.stepNumber === undefined) return 'Completed';
    const at = `Step ${Math.min(row.stepNumber, total)} of ${total}`;
    return row.status === 'exited' || row.status === 'failed'
      ? `Stopped at ${at.toLowerCase()}`
      : at;
  };

  /** HubSpot's Details: when it starts or its next step runs, why it paused or ended. */
  const detailsOf = (row: SequenceEnrollment): string => {
    const b = bucketOf(row);
    if (row.waitingOnTask) return 'When the task is done';
    if (b === 'scheduled' || b === 'in_progress') {
      if (!row.nextRunAt || row.status !== 'active') return '-';
      const on = day(row.nextRunAt, timeZone);
      if (b === 'scheduled') {
        const days = daysUntil(row.nextRunAt, today, timeZone);
        return days > 0 ? `Starts in ${plural(days, 'day')} on ${on}` : `Starts on ${on}`;
      }
      return `${stepText(row)} next step on ${on}`;
    }
    const why = reasonOf(row);
    const when = b === 'paused' ? row.pausedAt : row.endedAt;
    return why ? `${why}${when ? ` · ${day(when, timeZone)}` : ''}` : '-';
  };

  /**
   * Retry or skip a failed step (HUB-198, POST /sequence-enrollments/:id/retry | skip): the
   * confirmation names the step and the error it failed with (GET /sequence-enrollments/:id).
   */
  const fixStep = async (row: SequenceEnrollment, action: SequenceStepFixAction) => {
    if (busyId) return;
    setBusyId(row.id);
    let failure: { step: string; error: string | null } | null = null;
    try {
      const detail = await getSequenceEnrollment(row.id);
      const run = detail.steps.find((s) => s.status === 'failed');
      failure = {
        step: stepText(row).replace(/^Stopped at s/, 'S'),
        error: run?.lastError ?? null,
      };
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
      setBusyId(null);
      return;
    }
    setBusyId(null);
    const ok = await confirm({
      title: action === 'retry' ? 'Retry step' : 'Skip step',
      message: (
        <>
          <p className="crm-mt-0">
            {failure.step} failed
            {failure.error ? (
              <>
                : <q>{failure.error}</q>
              </>
            ) : (
              '.'
            )}
          </p>
          <p className="crm-mb-0">
            {action === 'retry'
              ? 'It runs again in the next sending window.'
              : 'The sequence goes on with the next step.'}
          </p>
        </>
      ),
      confirmLabel: action === 'retry' ? 'Retry step' : 'Skip step',
    });
    if (!ok) return;
    setBusyId(row.id);
    try {
      await controlSequenceEnrollment(row.id, action);
      onChanged?.();
      toast(action === 'retry' ? 'The step will run again.' : 'Step skipped.', 'success');
      // Its step number, status and the counts come from the list: read it again.
      void load();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
    } finally {
      setBusyId(null);
    }
  };

  const act = async (row: SequenceEnrollment, action: SequenceControlAction) => {
    if (busyId) return;
    if (
      action === 'stop' &&
      !(await confirm({
        title: 'Unenroll contact',
        message: `Unenroll ${row.contactName || row.contactEmail || 'this contact'} from the sequence? No more steps will run for them.`,
        confirmLabel: 'Unenroll',
        danger: true,
      }))
    ) {
      return;
    }
    setBusyId(row.id);
    try {
      await controlSequenceEnrollment(row.id, action);
      onChanged?.();
      toast(
        action === 'pause'
          ? 'Enrollment paused.'
          : action === 'resume'
            ? 'Enrollment resumed.'
            : 'Contact unenrolled.',
        'success',
      );
      // The row may leave the status shown, and the counts change: read the page again.
      void load();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
    } finally {
      setBusyId(null);
    }
  };

  /** HubSpot's "N selected · Pause · Resume · Unenroll": the same actions on the checked rows. */
  const bulk = async (action: SequenceControlAction) => {
    if (bulkBusy || selected.size === 0) return;
    const ids = [...selected];
    if (
      action === 'stop' &&
      !(await confirm({
        title: 'Unenroll contacts',
        message: `Unenroll ${plural(ids.length, 'contact')} from the sequence? No more steps will run for them.`,
        confirmLabel: 'Unenroll',
        danger: true,
      }))
    ) {
      return;
    }
    setBulkBusy(true);
    try {
      const result = await bulkControlSequenceEnrollments({ ids, action });
      const verb = action === 'pause' ? 'paused' : action === 'resume' ? 'resumed' : 'unenrolled';
      const refused = result.data.find((r) => r.result === 'refused')?.message;
      toast(
        result.refused
          ? `${plural(result.updated, 'enrollment')} ${verb}, ${result.refused} not changed${refused ? `: ${refused}` : ''}.`
          : `${plural(result.updated, 'enrollment')} ${verb}.`,
        result.refused ? 'info' : 'success',
        { durationMs: result.refused ? 9000 : undefined },
      );
      onChanged?.();
      void load();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
    } finally {
      setBulkBusy(false);
    }
  };

  /** "Create segment": the contacts of every enrollment under the filters, not just this page. */
  const openSegment = async () => {
    if (segmentBusy) return;
    setSegmentBusy(true);
    try {
      const ids = new Set<string>();
      let cursor: string | undefined;
      let pages = 0;
      do {
        const next = await listSequenceEnrollments(sequenceId, {
          ...filters,
          ...(bucket !== 'all' && { bucket }),
          ...(reason && { reason }),
          limit: SEGMENT_PAGE,
          cursor,
        });
        for (const r of next.data) ids.add(r.contactId);
        cursor = next.nextCursor ?? undefined;
        pages += 1;
      } while (cursor && pages < SEGMENT_MAX_PAGES);
      if (cursor) {
        toast(`Only the newest ${SEGMENT_PAGE * SEGMENT_MAX_PAGES} enrollments are added.`, 'info');
      }
      setSegmentIds([...ids]);
      setSegmentOpen(true);
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
    } finally {
      setSegmentBusy(false);
    }
  };

  const pages = Math.max(1, Math.ceil(total / perPage));
  const everyone = rows?.length ? rows.every((r) => selected.has(r.id)) : false;
  const count = (key: Bucket) =>
    key === 'all' ? (breakdown?.all ?? 0) : (breakdown?.buckets[key] ?? 0);

  return (
    <div className="seqe">
      <nav className="seqe-buckets" aria-label="Enrollment statuses">
        {BUCKETS.map((b) => {
          const subs = b.key === 'all' ? undefined : SUBS[b.key];
          const expanded = bucket === b.key && Boolean(subs);
          return (
            <div key={b.key}>
              <button
                type="button"
                className={cn('seqe-bucket', bucket === b.key && !reason && 'is-active')}
                aria-pressed={bucket === b.key && !reason}
                aria-expanded={subs ? expanded : undefined}
                onClick={() => {
                  setBucket(b.key);
                  setReason('');
                }}
              >
                {b.key === 'all' ? null : (
                  <span className={cn('seqe-dot', `seqe-dot--${b.key}`)} aria-hidden />
                )}
                <span className="seqe-bucket__label">{b.label}</span>
                <span className="seqe-bucket__count">{count(b.key)}</span>
                {subs ? (
                  <svg viewBox="0 0 24 24" width="12" height="12" aria-hidden>
                    <path
                      d={expanded ? 'm7 14 5-5 5 5' : 'm7 10 5 5 5-5'}
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                    />
                  </svg>
                ) : null}
              </button>
              {expanded
                ? subs?.map((sub) => (
                    <button
                      key={sub.key}
                      type="button"
                      className={cn(
                        'seqe-bucket seqe-bucket--sub',
                        reason === sub.key && 'is-active',
                      )}
                      aria-pressed={reason === sub.key}
                      onClick={() => setReason(reason === sub.key ? '' : sub.key)}
                    >
                      <span className="seqe-bucket__label">{sub.label}</span>
                      <span className="seqe-bucket__count">{breakdown?.reasons[sub.key] ?? 0}</span>
                    </button>
                  ))
                : null}
            </div>
          );
        })}
      </nav>

      <section className="seqe-main" aria-label="Enrollments">
        <div className="seqe-bar">
          <label className="seqe-search">
            <input
              type="search"
              placeholder="Search contacts"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              aria-label="Search contacts"
            />
            <svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor">
              <circle cx="11" cy="11" r="6.5" strokeWidth="1.8" />
              <path d="m16 16 4 4" strokeWidth="1.8" strokeLinecap="round" />
            </svg>
          </label>
          <ValuesFilter
            label="Company"
            selected={companyIds}
            onChange={setCompanyIds}
            options={(breakdown?.companies ?? []).map((c) => ({ value: c.id, label: c.name }))}
            searchLabel="Search companies"
          />
          <EnrolledByFilter selected={enrolledBy} onChange={setEnrolledBy} />
          <DateRangeFilter value={range} onChange={setRange} />
          {/* #86: HubSpot's "Create segment" from the enrollments shown. */}
          <button
            type="button"
            className={cn(
              'btn-crm btn-crm--ghost btn-crm--sm seqe-bar__end',
              segmentBusy && 'is-loading',
            )}
            disabled={!total || segmentBusy}
            aria-busy={segmentBusy}
            title={total ? undefined : 'No enrollments to add'}
            onClick={() => void openSegment()}
          >
            Create segment
          </button>
        </div>

        {error ? <p className="seqm-empty crm-text-danger">{error}</p> : null}

        {selected.size > 0 ? (
          <div className="seqe-bar" role="toolbar" aria-label="Selected enrollments">
            <strong>{selected.size} selected</strong>
            {(
              [
                ['pause', 'Pause'],
                ['resume', 'Resume'],
                ['stop', 'Unenroll'],
              ] as const
            ).map(([action, label]) => (
              <button
                key={action}
                type="button"
                className="btn-crm btn-crm--ghost btn-crm--sm"
                disabled={bulkBusy}
                onClick={() => void bulk(action)}
              >
                {label}
              </button>
            ))}
          </div>
        ) : null}

        {rows !== null && rows.length === 0 && !error ? (
          <p className="seqm-empty">No enrollments match your search.</p>
        ) : (
          <div className="seqm-table-wrap">
            <table className="seqm-table seqe-table">
              <thead>
                <tr>
                  <th scope="col" style={{ width: 32 }}>
                    <input
                      type="checkbox"
                      aria-label="Select all enrollments on this page"
                      checked={everyone}
                      disabled={!rows?.length}
                      onChange={() =>
                        setSelected(everyone ? new Set() : new Set((rows ?? []).map((r) => r.id)))
                      }
                    />
                  </th>
                  <th scope="col">Contact</th>
                  <th scope="col">Company</th>
                  <th scope="col">Enrolled</th>
                  <th scope="col">Engagement</th>
                  <th scope="col">Latest step</th>
                  <th scope="col">Status</th>
                  <th scope="col">Details</th>
                  <th scope="col" className="seqe-actions">
                    <span className="crm-visually-hidden">Actions</span>
                  </th>
                </tr>
              </thead>
              <tbody>
                {rows === null ? (
                  <tr>
                    <td colSpan={9} className="seqm-empty">
                      Loading enrollments…
                    </td>
                  </tr>
                ) : (
                  rows.map((row) => {
                    const b = bucketOf(row);
                    const replied =
                      row.exitReason === 'replied' || row.exitReason === 'colleague_replied';
                    const booked =
                      row.exitReason === 'meeting_booked' ||
                      row.exitReason === 'colleague_meeting_booked';
                    const label = row.contactName ?? row.contactEmail ?? 'Contact';
                    return (
                      <tr key={row.id}>
                        <td>
                          <input
                            type="checkbox"
                            aria-label={`Select ${label}`}
                            checked={selected.has(row.id)}
                            onChange={() =>
                              setSelected((current) => {
                                const next = new Set(current);
                                if (!next.delete(row.id)) next.add(row.id);
                                return next;
                              })
                            }
                          />
                        </td>
                        <td>
                          <Link className="seqe-contact" href={`/contacts/${row.contactId}`}>
                            <strong>{label}</strong>
                            {row.contactJobTitle ? (
                              <span>{row.contactJobTitle}</span>
                            ) : row.contactEmail && row.contactName !== row.contactEmail ? (
                              <span>{row.contactEmail}</span>
                            ) : null}
                          </Link>
                        </td>
                        <td>{row.companyName ?? '-'}</td>
                        {/* #86: as HubSpot, the date and who enrolled share a column. */}
                        <td>
                          {day(row.createdAt, timeZone)}
                          <span className="seqe-by">by {enrolledByName(row.enrolledBy)}</span>
                        </td>
                        <td>
                          {replied || booked ? (
                            <span className="seqe-status seqe-status--finished">
                              {replied ? 'Replied' : 'Meeting booked'}
                            </span>
                          ) : null}
                          {row.opens || row.clicks ? (
                            <span className="seqe-engage">
                              {row.opens ?? 0} {row.opens === 1 ? 'Open' : 'Opens'}{' '}
                              {row.clicks ?? 0} {row.clicks === 1 ? 'Click' : 'Clicks'}
                            </span>
                          ) : replied || booked ? null : (
                            <span className="crm-text-muted">None yet</span>
                          )}
                        </td>
                        <td>
                          {day(row.latestStepAt ?? null, timeZone)}
                          <span className="seqe-by">
                            {stepText(row)}
                            {row.stepType
                              ? ` (${STEP_TYPE_TEXT[row.stepType] ?? row.stepType})`
                              : ''}
                          </span>
                        </td>
                        <td>
                          <span className={cn('seqe-status', `seqe-status--${b}`)}>
                            {statusText(row)}
                          </span>
                        </td>
                        <td>
                          <span className="seqe-reason">{detailsOf(row)}</span>
                        </td>
                        <td className="crm-text-end seqe-actions">
                          {row.status === 'active' ||
                          row.status === 'paused' ||
                          row.status === 'failed' ? (
                            <Kebab
                              label="Enrollment actions"
                              text="Actions"
                              items={[
                                {
                                  key: 'edit',
                                  label: 'Edit',
                                  disabled: true,
                                  title:
                                    'Editing the emails of an enrolled contact is not available yet',
                                  onSelect: () => undefined,
                                },
                                ...(row.status === 'active'
                                  ? [
                                      {
                                        key: 'pause',
                                        label: 'Pause',
                                        disabled: busyId !== null,
                                        onSelect: () => void act(row, 'pause'),
                                      },
                                    ]
                                  : row.status === 'paused'
                                    ? [
                                        {
                                          key: 'resume',
                                          label: 'Resume',
                                          disabled: busyId !== null,
                                          onSelect: () => void act(row, 'resume'),
                                        },
                                      ]
                                    : [
                                        {
                                          key: 'retry',
                                          label: 'Retry step',
                                          disabled: busyId !== null,
                                          onSelect: () => void fixStep(row, 'retry'),
                                        },
                                        {
                                          key: 'skip',
                                          label: 'Skip step',
                                          disabled: busyId !== null,
                                          onSelect: () => void fixStep(row, 'skip'),
                                        },
                                      ]),
                                ...(row.status === 'failed'
                                  ? []
                                  : [
                                      {
                                        key: 'stop',
                                        label: 'Unenroll',
                                        separated: true,
                                        disabled: busyId !== null,
                                        onSelect: () => void act(row, 'stop'),
                                      },
                                    ]),
                              ]}
                            />
                          ) : null}
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>
        )}

        {rows !== null && total > 0 ? (
          <div className="seqe-bar" style={{ justifyContent: 'center' }}>
            <Pager
              page={page}
              pages={pages}
              onChange={(next) => setPageState({ page: next, key: filterKey })}
            />
            <label className="crm-fs-8 crm-text-muted">
              <select
                className="input"
                aria-label="Rows per page"
                value={perPage}
                onChange={(e) => setPerPage(Number(e.target.value))}
              >
                {PER_PAGE_OPTIONS.map((n) => (
                  <option key={n} value={n}>
                    {n} per page
                  </option>
                ))}
              </select>
            </label>
          </div>
        ) : null}
      </section>
      {confirmDialog}
      <CreateSegmentDialog
        open={segmentOpen}
        contactIds={segmentIds}
        onClose={() => setSegmentOpen(false)}
      />
    </div>
  );
}

/** Records per POST /lists/:id/members. */
const MEMBERS_PER_CALL = 100;

/**
 * #86: HubSpot's "Create a segment" (Segment name, Description): a static contact segment of the
 * contacts of the enrollments shown (after the status, search and filters).
 */
export function CreateSegmentDialog({
  open,
  contactIds,
  onClose,
}: {
  open: boolean;
  contactIds: string[];
  onClose: () => void;
}) {
  const toast = useToast();
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    setName('');
    setDescription('');
    setError(null);
  }, [open]);

  const close = busy ? () => {} : onClose;

  const submit = async () => {
    if (busy) return;
    if (!name.trim()) {
      setError('Give the segment a name.');
      return;
    }
    setBusy(true);
    setError(null);
    try {
      const list = await createList({
        name: name.trim(),
        description: description.trim() || null,
        objectType: 'contact',
        listType: 'static',
      });
      for (let i = 0; i < contactIds.length; i += MEMBERS_PER_CALL) {
        await addListMembers(list.id, contactIds.slice(i, i + MEMBERS_PER_CALL));
      }
      toast(
        `Segment "${list.name}" created with ${plural(contactIds.length, 'contact')}.`,
        'success',
      );
      onClose();
    } catch (err) {
      setError(
        isApiError(err) && err.isConflict
          ? 'A segment with this name already exists.'
          : errorText(err),
      );
    } finally {
      setBusy(false);
    }
  };

  const id = 'seqeSegmentDialog';
  return (
    <CrmModal id={id} open={open} onClose={close}>
      <ModalHeader id={id} title="Create a segment" onClose={close} />
      <form
        noValidate
        onSubmit={(e) => {
          e.preventDefault();
          void submit();
        }}
      >
        <div className="modal__body">
          {error ? <Alert tone="danger">{error}</Alert> : null}
          <div className="field">
            <label className="field__label" htmlFor="seqeSegmentName">
              Segment name
            </label>
            <input
              id="seqeSegmentName"
              className="input"
              value={name}
              maxLength={191}
              onChange={(e) => setName(e.target.value)}
            />
          </div>
          <div className="field">
            <label className="field__label" htmlFor="seqeSegmentDescription">
              Description
            </label>
            <input
              id="seqeSegmentDescription"
              className="input"
              value={description}
              maxLength={500}
              onChange={(e) => setDescription(e.target.value)}
            />
          </div>
          <p className="crm-fs-8 crm-text-muted crm-mb-0">
            A static segment of the {plural(contactIds.length, 'contact')} in the enrollments shown.
          </p>
        </div>
        <div className="modal__footer">
          <button type="button" className="btn-crm btn-crm--outline" onClick={close}>
            Cancel
          </button>
          <button
            type="submit"
            className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
            disabled={busy || !name.trim()}
            aria-busy={busy}
          >
            Create segment
          </button>
        </div>
      </form>
    </CrmModal>
  );
}
