'use client';

import Link from 'next/link';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { useToast } from '@/components/crm/ToastProvider';
import { listFormChoices } from '@/features/sequences/api.client';
import type { Sequence, SequenceSettings } from '@/features/sequences/types';
import { ConfirmDialog } from '@/features/tasks/ui/ConfirmDialog';
import {
  archiveWorkflow,
  createWorkflow,
  getWorkflow,
  listWorkflows,
  publishWorkflow,
  turnOffWorkflow,
  turnOnWorkflow,
} from '@/features/workflows/api.client';
import type { WorkflowDefinition, WorkflowSummary } from '@/features/workflows/types';
import { useWorkflowAccess } from '@/features/workflows/ui/shared';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

/** Pages of 100 workflows read for the list, and workflow details loaded at once. */
const MAX_WORKFLOW_PAGES = 20;
const DETAIL_BATCH = 10;

/** Folder the automations' workflows are kept in (they show on the Workflows page too). */
const AUTOMATION_FOLDER = 'Sequence automations';

type SenderType = 'contact_owner' | 'sequence_owner';
type ActionKind = 'enroll' | 'unenroll';
/** The two triggers (design: Form submission / Page view cards). */
type TriggerKind = 'form' | 'page';
/** Sequences #88: HubSpot's "at least one URL equal to" / "containing". */
type UrlMatch = 'equals' | 'contains';

/** The workflow trigger events the automations start on. */
const TRIGGER_EVENTS: Record<TriggerKind, string> = {
  form: 'form.submitted',
  page: 'page.viewed',
};

/** One form-submission or page-view automation: a workflow made by this tab (or shaped like one). */
interface Automation {
  workflow: WorkflowSummary;
  trigger: TriggerKind;
  formId: string | null;
  /** Page view automations: the URL and how it matches. */
  url: string | null;
  urlMatch: UrlMatch;
  action: ActionKind;
  sequenceId: string;
  delayMinutes: number;
}

function FormIcon() {
  return (
    <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" aria-hidden>
      <rect x="5" y="3" width="14" height="18" rx="2" strokeWidth="1.8" />
      <path d="M8.5 8h7M8.5 12h7M8.5 16h4" strokeWidth="1.8" strokeLinecap="round" />
    </svg>
  );
}

function PageIcon() {
  return (
    <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" aria-hidden>
      <rect x="3.5" y="4" width="17" height="16" rx="2" strokeWidth="1.8" />
      <path d="M3.5 9h17M9 9v11" strokeWidth="1.8" />
    </svg>
  );
}

function SequenceActionIcon() {
  return (
    <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" aria-hidden>
      <circle cx="6" cy="6" r="2.5" strokeWidth="1.8" />
      <circle cx="18" cy="18" r="2.5" strokeWidth="1.8" />
      <path d="M8.5 6H14a3 3 0 0 1 3 3v6.5" strokeWidth="1.8" />
    </svg>
  );
}

/** Reads a workflow's definition back into an automation; null if it isn't one. */
function automationOf(
  workflow: WorkflowSummary,
  definition: Record<string, unknown> | null,
): Automation | null {
  if (!definition) return null;
  type Branch = { event?: string; formId?: string; url?: string; urlMatch?: UrlMatch };
  const raw = definition.trigger as (Branch & { type?: string; events?: Branch[] }) | undefined;
  if (raw?.type !== 'event') return null;
  // A-04: a workflow may start on several events; the form or page view one is the automation.
  const branches = raw.events?.length ? raw.events : [raw];
  const trigger =
    branches.find((b) => b.event === TRIGGER_EVENTS.form || b.event === TRIGGER_EVENTS.page) ?? raw;
  const kind =
    trigger.event === TRIGGER_EVENTS.form
      ? 'form'
      : trigger.event === TRIGGER_EVENTS.page
        ? 'page'
        : null;
  if (!kind || (kind === 'page' && !trigger.url)) return null;
  const steps = (definition.steps ?? []) as Array<Record<string, unknown>>;
  const action = steps.find(
    (s) =>
      s.type === 'action' &&
      (s.action === 'enroll_in_sequence' || s.action === 'unenroll_from_sequence'),
  );
  const config = (action?.config ?? {}) as { sequenceId?: string };
  if (!action || !config.sequenceId) return null;
  const delay = steps.find((s) => s.type === 'delay')?.delay as
    { kind?: string; amount?: number; unit?: string } | undefined;
  const minutes =
    delay?.kind === 'duration' && typeof delay.amount === 'number'
      ? delay.amount * ({ minutes: 1, hours: 60, days: 1440, weeks: 10080 }[delay.unit ?? ''] ?? 0)
      : 0;
  return {
    workflow,
    trigger: kind,
    formId: trigger.formId ?? null,
    url: trigger.url ?? null,
    urlMatch: trigger.urlMatch === 'contains' ? 'contains' : 'equals',
    action: action.action === 'enroll_in_sequence' ? 'enroll' : 'unenroll',
    sequenceId: config.sequenceId,
    delayMinutes: minutes,
  };
}

/** GAP-r61: the design's Action column ("Enroll", "Enroll after N min", "Unenroll"). */
function actionText(a: Pick<Automation, 'action' | 'delayMinutes'>): string {
  if (a.action === 'unenroll') return 'Unenroll';
  return a.delayMinutes > 0 ? `Enroll after ${a.delayMinutes} min` : 'Enroll';
}

/** GAP-r61: the design's Trigger column. */
function triggerText(a: Pick<Automation, 'trigger' | 'url' | 'urlMatch'>, form: string | null) {
  if (a.trigger === 'page') {
    return `Contact views a URL ${a.urlMatch === 'contains' ? 'containing' : 'equal to'} "${a.url ?? ''}"`;
  }
  return form ? `Contact submits "${form}"` : 'Contact submits any form';
}

/**
 * Automate tab: start or end sequences when a lead submits a form or views a page (Sequences
 * #88: page views from the website tracking code).
 * With `sequenceId` (the sequence editor's Automate tab) only that sequence's automations show.
 */
export function SequencesAutomateTab({
  sequences,
  sequenceId,
  settings,
  canEditSettings = false,
  onSettingsChange,
  unsaved = false,
}: {
  sequences: Sequence[];
  sequenceId?: string;
  /** In the sequence editor: its settings (unsaved edits too), so the reply / meeting
   *  unenroll rules can be switched; saved with the editor's Save (QA 16 Oct #117). */
  settings?: SequenceSettings;
  canEditSettings?: boolean;
  onSettingsChange?: (settings: SequenceSettings) => void;
  /** A sequence not saved yet: the unenroll rules are held in the editor's draft and saved with
   *  its first Save; automations are workflows on a saved sequence, so none can be made yet. */
  unsaved?: boolean;
}) {
  const access = useWorkflowAccess();
  const toast = useToast();
  const [automations, setAutomations] = useState<Automation[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [forms, setForms] = useState<Array<{ id: string; name: string }> | null>(null);
  /** Why the forms could not be read (an empty list is not an error; QA 16 Oct #133). */
  const [formsError, setFormsError] = useState<string | null>(null);
  /** The drawer: open, and the card it was opened from (null trigger: it asks which). */
  const [drawer, setDrawer] = useState<{ trigger: TriggerKind | null } | null>(null);
  const [busyId, setBusyId] = useState<string | null>(null);
  const [deleting, setDeleting] = useState<Automation | null>(null);

  const load = useCallback(async () => {
    if (!access.canView || unsaved) {
      setLoading(false);
      return;
    }
    setLoading(true);
    setError(null);
    try {
      // Every workflow with a sequence action (all pages), then the form- and page-view-triggered
      // ones' details,
      // a few at a time. A workflow that fails to load (e.g. deleted meanwhile) is left out.
      const workflows: Awaited<ReturnType<typeof listWorkflows>>['data'] = [];
      let cursor: string | undefined;
      for (let pages = 0; pages < MAX_WORKFLOW_PAGES; pages++) {
        const page = await listWorkflows({
          actionType: ['enroll_in_sequence', 'unenroll_from_sequence'],
          sortBy: 'createdAt',
          sortDir: 'desc',
          limit: 100,
          cursor,
        });
        workflows.push(...page.data);
        if (!page.nextCursor) break;
        cursor = page.nextCursor;
      }
      const events = Object.values(TRIGGER_EVENTS);
      // A-04: any of a workflow's OR'd events (`event` alone from an older API).
      const candidates = workflows.filter((w) =>
        (w.trigger?.events ?? [w.trigger?.event ?? '']).some((e) => events.includes(e)),
      );
      const found: Automation[] = [];
      for (let i = 0; i < candidates.length; i += DETAIL_BATCH) {
        const batch = candidates.slice(i, i + DETAIL_BATCH);
        const details = await Promise.allSettled(batch.map((w) => getWorkflow(w.id)));
        details.forEach((d, k) => {
          if (d.status !== 'fulfilled') return;
          const definition = d.value.definition ?? d.value.draft?.definition ?? null;
          const a = automationOf(batch[k]!, definition);
          if (a) found.push(a);
        });
      }
      setAutomations(found);
    } catch (err) {
      setError(errorText(err));
    } finally {
      setLoading(false);
    }
  }, [access.canView, unsaved]);

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

  useEffect(() => {
    let cancelled = false;
    listFormChoices().then(
      (res) => {
        if (!cancelled) setForms(res.data.filter((f) => !f.archived));
      },
      (err) => {
        if (cancelled) return;
        setForms([]);
        setFormsError(errorText(err));
      },
    );
    return () => {
      cancelled = true;
    };
  }, []);

  const shown = sequenceId ? automations.filter((a) => a.sequenceId === sequenceId) : automations;
  const scoped = sequenceId || unsaved ? sequences.find((s) => s.id === sequenceId) : undefined;
  const inEditor = Boolean(sequenceId) || unsaved;
  // Workflows can only use shared sequences (D-5: there is no draft status; a sequence with step
  // problems is refused when a workflow enrolls into it). Sequences QA manage BUG-05: the option
  // is named as in Settings and Manage sharing.
  const scopedNote = unsaved
    ? null
    : scoped && scoped.visibility !== 'shared'
      ? 'Automations can only use shared sequences: set Settings > Who can use this sequence to Everyone, then save.'
      : null;

  const formName = (id: string | null) =>
    id ? (forms?.find((f) => f.id === id)?.name ?? 'a form') : null;
  const sequenceName = (id: string) => sequences.find((s) => s.id === id)?.name ?? null;

  const toggle = async (a: Automation) => {
    if (busyId) return;
    setBusyId(a.workflow.id);
    try {
      if (a.workflow.status === 'on') {
        await turnOffWorkflow(a.workflow.id, { mode: 'let_finish' });
        toast('Automation turned off');
      } else {
        await turnOnWorkflow(a.workflow.id, { enrollExisting: false });
        toast('Automation turned on', 'success');
      }
      await load();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
    } finally {
      setBusyId(null);
    }
  };

  const remove = async () => {
    if (!deleting || busyId) return;
    setBusyId(deleting.workflow.id);
    try {
      if (deleting.workflow.status === 'on') {
        await turnOffWorkflow(deleting.workflow.id, { mode: 'let_finish' });
      }
      await archiveWorkflow(deleting.workflow.id);
      toast('Automation deleted');
      setDeleting(null);
      await load();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 9000 });
    } finally {
      setBusyId(null);
    }
  };

  if (!access.canView) {
    return (
      <p className="seqm-empty">
        Your permissions do not allow viewing sequence automations (they are workflows).
      </p>
    );
  }

  // Automations use shared sequences only: no form trigger for one shared with nobody.
  const cannotCreate = unsaved
    ? undefined
    : !access.canEdit
      ? 'You need permission to manage workflows'
      : scoped && scoped.visibility !== 'shared'
        ? 'Share this sequence with everyone first (Settings > Who can use this sequence)'
        : undefined;
  const exitRules: Array<{
    text: string;
    key?: 'unenrollOnReply' | 'unenrollOnMeeting';
    /** SEQ-R-B7: HubSpot's "Unenroll [the contact | all contacts at the company]". */
    companyKey?: 'unenrollCompanyOnReply' | 'unenrollCompanyOnMeeting';
  }> = [
    {
      text: 'When a contact replies to any email (out-of-office replies don’t count)',
      key: 'unenrollOnReply',
      companyKey: 'unenrollCompanyOnReply',
    },
    {
      text: 'When a contact books a meeting',
      key: 'unenrollOnMeeting',
      companyKey: 'unenrollCompanyOnMeeting',
    },
    { text: 'When an email to the contact bounces' },
    { text: 'When the contact unsubscribes' },
  ];

  return (
    <div className="seqz">
      <header className="seqz-head">
        <h3 className="seqz-head__title">
          {inEditor ? 'Automate your sequence' : 'Automate your sequences'}
        </h3>
        <p className="seqz-head__sub">
          {inEditor
            ? 'Choose what actions will unenroll this sequence.'
            : 'Automatically start or end sequences when your lead visits your website or submits a form.'}
        </p>
        {scopedNote ? <p className="seqz-head__sub crm-mt-2">{scopedNote}</p> : null}
      </header>

      {/* QA 14 Oct #34: the exits are built in (HUB-197); HubSpot lists them here. Replies and
          meetings can be switched off per sequence (QA 16 Oct #117); bounces and unsubscribes
          always unenroll. */}
      <section className="seqz-exits" aria-label="Automatic unenrollment">
        <h4 className="seqz-exits__title">Unenroll automatically</h4>
        <ul className="seqz-exits__list">
          {exitRules.map(({ text, key, companyKey }) => {
            const on = key && settings ? settings[key] !== false : true;
            return (
              <li key={text}>
                <span>{text}</span>
                {companyKey && settings && onSettingsChange && on ? (
                  <label className="seqz-exits__then seqz-exits__switch">
                    Unenroll
                    <select
                      className="input seqz-exits__who"
                      aria-label={`${text}: who to unenroll`}
                      value={settings[companyKey] ? 'company' : 'contact'}
                      disabled={!canEditSettings}
                      onChange={(e) =>
                        onSettingsChange({
                          ...settings,
                          [companyKey]: e.target.value === 'company',
                        })
                      }
                    >
                      <option value="contact">the contact</option>
                      <option value="company">all contacts at the company</option>
                    </select>
                    from this sequence
                  </label>
                ) : null}
                {key && settings && onSettingsChange ? (
                  <label className="seqz-switch seqz-exits__then">
                    <input
                      type="checkbox"
                      role="switch"
                      aria-label={`${text}: unenroll`}
                      checked={on}
                      disabled={!canEditSettings}
                      onChange={(e) => onSettingsChange({ ...settings, [key]: e.target.checked })}
                    />
                    <span className="seqz-switch__track" aria-hidden />
                    {on ? 'On' : 'Off'}
                  </label>
                ) : (
                  <span className="seqz-exits__then">
                    {key ? 'Unenroll · On (set per sequence)' : 'Unenroll · Always on'}
                  </span>
                )}
              </li>
            );
          })}
        </ul>
        {settings && onSettingsChange ? (
          <p className="seqz-head__sub crm-mt-2 crm-mb-0">Changes are saved with the sequence.</p>
        ) : null}
      </section>

      {inEditor ? (
        <section className="seqz-custom" aria-label="Custom automations">
          <h4 className="seqz-exits__title">Custom automations</h4>
          <p className="seqz-head__sub">
            Automatically enroll or unenroll contacts when they submit a form or view a page on your
            website.
          </p>
          <button
            type="button"
            className="btn-crm btn-crm--outline seqm-pill crm-mt-2"
            disabled={cannotCreate !== undefined}
            title={cannotCreate}
            onClick={() =>
              unsaved
                ? toast('Save this sequence first, then create an automation for it.', 'info')
                : setDrawer({ trigger: null })
            }
          >
            Create an automation
          </button>
        </section>
      ) : (
        <div className="seqz-cards">
          <article className="seqz-card">
            <span className="seqz-card__icon seqz-card__icon--form">
              <FormIcon />
            </span>
            <h4 className="seqz-card__title">Form submission</h4>
            <p className="seqz-card__text">
              Automatically enroll or unenroll leads from a sequence when they submit a form on your
              website.
            </p>
            <button
              type="button"
              className="btn-crm btn-crm--outline seqm-pill"
              disabled={cannotCreate !== undefined}
              title={cannotCreate}
              onClick={() => setDrawer({ trigger: 'form' })}
            >
              Create automation
            </button>
          </article>
          {/* Sequences #88: page views come from the website tracking code (Settings > Tracking
            code); contacts it knows start these automations. */}
          <article className="seqz-card">
            <span className="seqz-card__icon seqz-card__icon--page">
              <PageIcon />
            </span>
            <h4 className="seqz-card__title">Page view</h4>
            <p className="seqz-card__text">
              Start a targeted sequence for a lead that shows buying intent by viewing a page on
              your website, such as a pricing page or product page.
            </p>
            <button
              type="button"
              className="btn-crm btn-crm--outline seqm-pill"
              disabled={cannotCreate !== undefined}
              title={cannotCreate}
              onClick={() => setDrawer({ trigger: 'page' })}
            >
              Create automation
            </button>
          </article>
        </div>
      )}

      {/* GAP-r61: as in the design, the list shows once there are automations. */}
      {!unsaved && (loading || error || shown.length > 0) ? (
        <section className="seqz-list" aria-label="Your automations">
          <h4 className="seqz-list__title">Your automations</h4>
          {error ? <p className="seqm-empty crm-text-danger">{error}</p> : null}
          <div className="seqm-table-wrap seqz-table-wrap">
            <table className="seqm-table">
              <thead>
                <tr>
                  <th scope="col">Trigger</th>
                  <th scope="col">Action</th>
                  <th scope="col">Sequence</th>
                  <th scope="col">Status</th>
                  <th scope="col">
                    <span className="crm-visually-hidden">Delete</span>
                  </th>
                </tr>
              </thead>
              <tbody>
                {loading && shown.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="seqm-empty">
                      Loading automations…
                    </td>
                  </tr>
                ) : (
                  shown.map((a) => {
                    const on = a.workflow.status === 'on';
                    const form = formName(a.formId);
                    const name = sequenceName(a.sequenceId);
                    return (
                      <tr key={a.workflow.id}>
                        <td>
                          <Link
                            className="seqz-trigger"
                            href={`/workflows/${a.workflow.id}`}
                            title="Open the workflow"
                          >
                            {triggerText(a, form)}
                          </Link>
                        </td>
                        <td>{actionText(a)}</td>
                        <td>
                          {name ? (
                            <Link className="seqm-name" href={`/sequences/${a.sequenceId}`}>
                              {name}
                            </Link>
                          ) : (
                            <span className="crm-text-muted">Deleted sequence</span>
                          )}
                        </td>
                        <td>
                          <label className="seqz-switch">
                            <input
                              type="checkbox"
                              role="switch"
                              checked={on}
                              disabled={!access.canEdit || busyId !== null}
                              onChange={() => void toggle(a)}
                              aria-label={`${on ? 'Turn off' : 'Turn on'} this automation`}
                            />
                            <span className="seqz-switch__track" aria-hidden />
                            <span>{on ? 'On' : 'Off'}</span>
                          </label>
                        </td>
                        <td className="crm-text-end">
                          <button
                            type="button"
                            className="seqz-delete"
                            aria-label="Delete automation"
                            title="Delete automation"
                            disabled={!access.canEdit || busyId !== null}
                            onClick={() => setDeleting(a)}
                          >
                            <svg
                              viewBox="0 0 24 24"
                              width="16"
                              height="16"
                              fill="none"
                              stroke="currentColor"
                              aria-hidden
                            >
                              <path
                                d="M5 7h14M10 11v6M14 11v6M6.5 7l1 12a1 1 0 0 0 1 1h7a1 1 0 0 0 1-1l1-12M9.5 7V4.5h5V7"
                                strokeWidth="1.7"
                                strokeLinecap="round"
                                strokeLinejoin="round"
                              />
                            </svg>
                          </button>
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>
        </section>
      ) : null}

      <AutomationDrawer
        open={drawer !== null}
        trigger={drawer?.trigger ?? null}
        onClose={() => setDrawer(null)}
        forms={forms}
        formsError={formsError}
        sequences={sequences}
        presetSequenceId={sequenceId}
        onCreated={() => {
          setDrawer(null);
          void load();
        }}
      />

      <ConfirmDialog
        id="seqAutoDeleteModal"
        open={Boolean(deleting)}
        title="Delete automation?"
        confirmLabel="Delete"
        busy={busyId !== null}
        onCancel={() => setDeleting(null)}
        onConfirm={() => void remove()}
      >
        New {deleting?.trigger === 'page' ? 'page views' : 'form submissions'} will no longer{' '}
        {deleting?.action === 'unenroll' ? 'unenroll' : 'enroll'} contacts. Contacts already in the
        sequence stay in it.
      </ConfirmDialog>
    </div>
  );
}

function AutomationDrawer({
  open,
  trigger,
  onClose,
  forms,
  formsError,
  sequences,
  presetSequenceId,
  onCreated,
}: {
  open: boolean;
  /** The card it was opened from: its trigger is picked (design: open(trigger)). */
  trigger: TriggerKind | null;
  onClose: () => void;
  forms: Array<{ id: string; name: string }> | null;
  formsError: string | null;
  sequences: Sequence[];
  /** Picked for the user when it can be used (the sequence editor's Automate tab). */
  presetSequenceId?: string;
  onCreated: () => void;
}) {
  const toast = useToast();
  const [step, setStep] = useState<1 | 2>(1);
  const [picked, setPicked] = useState<TriggerKind | null>(trigger);
  const [formMode, setFormMode] = useState<'any' | 'specific' | null>(null);
  const [formId, setFormId] = useState('');
  const [urlMatch, setUrlMatch] = useState<UrlMatch | null>(null);
  const [url, setUrl] = useState('');
  const [action, setAction] = useState<ActionKind | null>(null);
  const [sequenceId, setSequenceId] = useState('');
  const [delay, setDelay] = useState('1');
  const [sender, setSender] = useState<SenderType | ''>('');
  const [useContactTimezone, setUseContactTimezone] = useState(true);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Every opening starts over.
  useEffect(() => {
    if (!open) return;
    setStep(1);
    setPicked(trigger);
    setFormMode(null);
    setFormId('');
    setUrlMatch(null);
    setUrl('');
    setAction(null);
    setSequenceId('');
    setDelay('1');
    setSender('');
    setUseContactTimezone(true);
    setError(null);
  }, [open, trigger]);

  // Workflows can only use shared sequences; enrolling can't use a deleted (archived) one.
  const usable = useMemo(
    () =>
      sequences.filter(
        (s) => s.visibility === 'shared' && (action !== 'enroll' || s.status !== 'archived'),
      ),
    [sequences, action],
  );

  useEffect(() => {
    if (presetSequenceId && usable.some((s) => s.id === presetSequenceId)) {
      setSequenceId(presetSequenceId);
    } else if (!usable.some((s) => s.id === sequenceId)) {
      setSequenceId('');
    }
  }, [presetSequenceId, usable, sequenceId]);

  const delayMinutes = Number(delay);
  const delayValid =
    delay.trim() === '' ||
    (Number.isInteger(delayMinutes) && delayMinutes >= 0 && delayMinutes <= 10_000);
  const triggerReady =
    picked === 'page'
      ? !!urlMatch && url.trim().length > 2
      : picked === 'form' && (formMode === 'any' || (formMode === 'specific' && !!formId));
  const actionReady =
    !!action && !!sequenceId && (action === 'unenroll' || (!!sender && delayValid));

  const create = async () => {
    if (!actionReady || busy) return;
    setBusy(true);
    setError(null);
    const page = picked === 'page';
    const form = !page && formMode === 'specific' ? forms?.find((f) => f.id === formId) : null;
    const pageUrl = url.trim();
    const sequence = sequences.find((s) => s.id === sequenceId);
    const minutes = delay.trim() === '' ? 0 : delayMinutes;
    const event = TRIGGER_EVENTS[page ? 'page' : 'form'];
    const definition: WorkflowDefinition = {
      formatVersion: 1,
      trigger: {
        type: 'event',
        event,
        ...(form ? { formId: form.id } : {}),
        ...(page ? { url: pageUrl, urlMatch: urlMatch ?? 'equals' } : {}),
      },
      // Every submission (or page view) counts, not only a contact's first.
      settings: {
        reEnrollment: { enabled: true, on: [event] },
        unenrollWhenNoLongerMatching: false,
      },
      steps: [
        ...(action === 'enroll' && minutes > 0
          ? [
              {
                id: 'delay',
                type: 'delay' as const,
                delay: { kind: 'duration', amount: minutes, unit: 'minutes' },
              },
            ]
          : []),
        {
          id: 'sequence',
          type: 'action' as const,
          action: action === 'enroll' ? 'enroll_in_sequence' : 'unenroll_from_sequence',
          config: action === 'enroll' ? { sequenceId, sender, useContactTimezone } : { sequenceId },
        },
      ] as WorkflowDefinition['steps'],
    };
    let createdId: string | null = null;
    try {
      const created = await createWorkflow({
        name: `${page ? `Page view ${pageUrl}` : form ? form.name : 'Any form'} → ${action === 'enroll' ? 'enroll in' : 'unenroll from'} ${sequence?.name ?? 'sequence'}`.slice(
          0,
          191,
        ),
        objectType: 'contact',
        folder: AUTOMATION_FOLDER,
        description: 'Made on Sequences > Automate.',
        definition,
      });
      createdId = created.id;
      const published = await publishWorkflow(created.id, created.updatedAt);
      await turnOnWorkflow(created.id, { enrollExisting: false, updatedAt: published.updatedAt });
      // GAP-r61: the design's toast.
      toast(
        `Automation created: ${action === 'enroll' ? 'enroll in' : 'unenroll from'} ${sequence?.name ?? 'sequence'}`,
        'success',
      );
      onCreated();
    } catch (err) {
      // A half-made workflow is not left behind.
      if (createdId) await archiveWorkflow(createdId).catch(() => {});
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  };

  const id = 'seqAutoDrawer';
  return (
    <CrmModal id={id} open={open} onClose={busy ? () => {} : onClose} drawer plainBackdrop>
      <form
        noValidate
        className="seqz-drawer"
        onSubmit={(e) => {
          e.preventDefault();
          if (step === 1 && triggerReady) setStep(2);
          else if (step === 2) void create();
        }}
      >
        <ModalHeader
          id={id}
          title={step === 1 ? 'Choose a workflow trigger' : 'Choose a workflow action'}
          onClose={busy ? () => {} : onClose}
        />
        <div className="modal__body">
          <ol className="seqz-stepper" aria-label="Progress">
            <li className={cn('seqz-stepper__item', step === 1 ? 'is-current' : 'is-done')}>
              <span className="seqz-stepper__dot" aria-hidden />
              Trigger
            </li>
            <li className={cn('seqz-stepper__item', step === 2 && 'is-current')}>
              <span className="seqz-stepper__dot" aria-hidden />
              Action
            </li>
          </ol>

          {error ? (
            <p className="seqz-error" role="alert">
              {error}
            </p>
          ) : null}

          {step === 1 ? (
            <>
              <p className="seqz-intro">
                Choose the event or criteria that needs to happen for contacts to be enrolled in the
                workflow.
              </p>
              {picked === null ? (
                <>
                  <p className="seqz-group">Contact activities</p>
                  <button type="button" className="seqz-choice" onClick={() => setPicked('form')}>
                    <span className="seqz-choice__icon">
                      <FormIcon />
                    </span>
                    Form submission
                  </button>
                  <button type="button" className="seqz-choice" onClick={() => setPicked('page')}>
                    <span className="seqz-choice__icon">
                      <PageIcon />
                    </span>
                    Page view
                  </button>
                </>
              ) : picked === 'page' ? (
                <>
                  {/* Sequences #88: HubSpot's two page view options, each with a URL. */}
                  <button type="button" className="seqz-back" onClick={() => setPicked(null)}>
                    <CrmIcon name="chevron-left" className="iconSize-16" />
                    Back
                  </button>
                  <p className="seqz-group">Page view</p>
                  {(
                    [
                      ['equals', 'Contact has viewed at least one URL equal to'],
                      ['contains', 'Contact has viewed at least one URL containing'],
                    ] as const
                  ).map(([mode, label]) => (
                    <label key={mode} className="seqz-radio">
                      <input
                        type="radio"
                        name="pageMode"
                        checked={urlMatch === mode}
                        onChange={() => setUrlMatch(mode)}
                      />
                      <span>{label}</span>
                    </label>
                  ))}
                  {urlMatch ? (
                    <div
                      className={cn(
                        'field crm-mt-2',
                        url.length > 0 && url.trim().length <= 2 && 'is-invalid',
                      )}
                    >
                      <label className="field__label" htmlFor="seqAutoUrl">
                        URL
                      </label>
                      <input
                        id="seqAutoUrl"
                        className="input"
                        value={url}
                        maxLength={2000}
                        autoComplete="off"
                        placeholder="e.g. https://example.com/pricing"
                        onChange={(e) => setUrl(e.target.value)}
                      />
                      <span className="field__error">Enter a URL.</span>
                      <p className="crm-fs-8 crm-text-muted crm-mt-1 crm-mb-0">
                        Counts views by known contacts on pages with the tracking code.
                      </p>
                    </div>
                  ) : null}
                </>
              ) : (
                <>
                  <button type="button" className="seqz-back" onClick={() => setPicked(null)}>
                    <CrmIcon name="chevron-left" className="iconSize-16" />
                    Back
                  </button>
                  <p className="seqz-group">Form submission</p>
                  <label className="seqz-radio">
                    <input
                      type="radio"
                      name="formMode"
                      checked={formMode === 'any'}
                      onChange={() => setFormMode('any')}
                    />
                    <span>Contact submits any form</span>
                  </label>
                  <label className="seqz-radio">
                    <input
                      type="radio"
                      name="formMode"
                      checked={formMode === 'specific'}
                      onChange={() => setFormMode('specific')}
                    />
                    <span>Contact submits a specific form</span>
                  </label>
                  {formMode === 'specific' ? (
                    <div className="field crm-mt-2">
                      <label className="field__label" htmlFor="seqAutoForm">
                        Form
                      </label>
                      <select
                        id="seqAutoForm"
                        className="input"
                        value={formId}
                        onChange={(e) => setFormId(e.target.value)}
                      >
                        <option value="">
                          {forms === null
                            ? 'Loading forms…'
                            : forms.length
                              ? 'Choose a form'
                              : formsError
                                ? 'Forms could not be loaded'
                                : 'No forms yet'}
                        </option>
                        {(forms ?? []).map((f) => (
                          <option key={f.id} value={f.id}>
                            {f.name}
                          </option>
                        ))}
                      </select>
                      {forms && forms.length === 0 ? (
                        <p className="crm-fs-8 crm-text-muted crm-mt-1 crm-mb-0">
                          {formsError
                            ? `${formsError} Pick "any form", or try again later.`
                            : 'There are no forms yet. Create one in Settings › Forms, or pick "any form".'}
                        </p>
                      ) : null}
                    </div>
                  ) : null}
                </>
              )}
            </>
          ) : (
            <>
              <p className="seqz-intro">
                Choose the event that happens after a contact is enrolled in the workflow.
              </p>
              <p className="seqz-group">Sequence actions</p>
              {(
                [
                  ['unenroll', 'Unenroll contact from a sequence'],
                  ['enroll', 'Enroll contact in a sequence'],
                ] as const
              ).map(([kind, label]) => (
                <button
                  key={kind}
                  type="button"
                  className={cn('seqz-choice', action === kind && 'is-active')}
                  aria-pressed={action === kind}
                  onClick={() => {
                    setAction(kind);
                    setSequenceId('');
                  }}
                >
                  <span className="seqz-choice__icon seqz-choice__icon--dark">
                    <SequenceActionIcon />
                  </span>
                  {label}
                </button>
              ))}
              {action ? (
                <div className="seqz-fields">
                  <div className="field">
                    <label className="field__label" htmlFor="seqAutoSequence">
                      Sequence
                    </label>
                    <select
                      id="seqAutoSequence"
                      className="input"
                      value={sequenceId}
                      onChange={(e) => setSequenceId(e.target.value)}
                    >
                      <option value="">
                        {usable.length ? 'Choose a sequence' : 'No sequence can be used'}
                      </option>
                      {usable.map((s) => (
                        <option key={s.id} value={s.id}>
                          {s.name}
                        </option>
                      ))}
                    </select>
                    <p className="crm-fs-8 crm-text-muted crm-mt-1 crm-mb-0">
                      Automations can use shared sequences
                      {action === 'enroll' ? ' that are active' : ''}.
                    </p>
                  </div>
                  {action === 'enroll' ? (
                    <>
                      <div className={cn('field', !delayValid && 'is-invalid')}>
                        <label className="field__label" htmlFor="seqAutoDelay">
                          Add an optional delay before enrolling (in minutes)
                        </label>
                        <input
                          id="seqAutoDelay"
                          className="input"
                          type="number"
                          min={0}
                          max={10000}
                          value={delay}
                          onChange={(e) => setDelay(e.target.value)}
                        />
                        <span className="field__error">Use a whole number from 0 to 10,000.</span>
                      </div>
                      <div className="field">
                        <label className="field__label" htmlFor="seqAutoSender">
                          Sender type
                        </label>
                        <select
                          id="seqAutoSender"
                          className="input"
                          value={sender}
                          onChange={(e) => setSender(e.target.value as SenderType | '')}
                        >
                          <option value="">Choose who sends</option>
                          <option value="contact_owner">Contact owner</option>
                          <option value="sequence_owner">Sequence owner</option>
                        </select>
                        <p className="crm-fs-8 crm-text-muted crm-mt-1 crm-mb-0">
                          Sent from their connected Gmail. Contacts without one are skipped.
                        </p>
                      </div>
                      <label className="check-row">
                        <span className="check">
                          <input
                            type="checkbox"
                            checked={useContactTimezone}
                            onChange={(e) => setUseContactTimezone(e.target.checked)}
                          />
                          <span className="check__box" aria-hidden />
                        </span>
                        Use contact&apos;s time zone
                      </label>
                    </>
                  ) : null}
                </div>
              ) : null}
            </>
          )}
        </div>
        {/* Drawer footers show in reverse (modal.css): the primary action comes out first. */}
        <div className="modal__footer">
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={onClose}
            disabled={busy}
          >
            Cancel
          </button>
          {step === 1 ? (
            <button type="submit" className="btn-crm btn-crm--primary" disabled={!triggerReady}>
              Next: Set workflow action
            </button>
          ) : (
            <>
              <button
                type="button"
                className="btn-crm btn-crm--ghost"
                onClick={() => setStep(1)}
                disabled={busy}
              >
                Back
              </button>
              <button
                type="submit"
                className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
                disabled={!actionReady || busy}
                aria-busy={busy}
              >
                Create
              </button>
            </>
          )}
        </div>
      </form>
    </CrmModal>
  );
}
