'use client';

/** The design's "New snippet" / "Edit snippet" modal (#mSnippet) with its formatting tools. */
import { useEffect, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { listCustomProperties } from '@/features/custom-properties/api.client';
import {
  shareLabel,
  shareOf,
  shareToApi,
  type ShareState,
} from '@/features/message-templates/model';
import { ShareDrawer, type ShareOptions } from '@/features/message-templates/ui/ShareDrawer';
import {
  TOKEN_GROUPS,
  customTokensOf,
  fieldLabel,
  type TokenField,
  type TokenGroupKey,
} from '@/features/sequences/ui/DynamicStepDrawers';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { errorText, isApiError } from '@/lib/api/errors';
import { createSnippet, updateSnippet, type Snippet, type SnippetFolder } from '../api.client';
import {
  SNIPPET_MAX_CHARS,
  fmtNum,
  mergeToken,
  normalizeShortcut,
  canWriteSnippets,
  isShortcutRefusal,
  SHORTCUT_TAKEN,
  shortcutError,
  snippetText,
} from '../model';
import { MtIcon, MtListbox, MtMenu, MtModal, MtModalHead, MtPop, MtSelect } from './mt';

const SWATCHES = [
  '#000000',
  '#475467',
  '#98a2b3',
  '#ffffff',
  '#c01048',
  '#e04f16',
  '#f28f23',
  '#fac515',
  '#067647',
  '#0e7c86',
  '#2456e6',
  '#7a3ed6',
  '#fde2e4',
  '#ffe8d1',
  '#fff4c2',
  '#d8f5e4',
  '#d6ecf5',
  '#e3dcfb',
];
const FONTS = [
  ['Sans Serif', 'Arial'],
  ['Serif', 'Georgia'],
  ['Monospace', 'Courier New'],
  ['Verdana', 'Verdana'],
  ['Times New Roman', 'Times New Roman'],
] as const;
const SIZES = ['10', '11', '12', '14', '16', '18', '24', '32'];
const SIZE_CMD: Record<string, string> = {
  '10': '2',
  '11': '3',
  '12': '3',
  '14': '4',
  '16': '5',
  '18': '6',
  '24': '7',
  '32': '7',
};

/** Snippets can name a ticket's fields too (email templates cannot). */
const SNIPPET_TOKEN_GROUPS = [
  ...TOKEN_GROUPS,
  { key: 'ticket', label: 'Ticket', fields: ['name', 'status', 'pipeline'] },
] as const;
type SnippetTokenGroup = TokenGroupKey | 'ticket';
const TICKET_LABELS: Record<string, string> = {
  name: 'Ticket name',
  status: 'Ticket status',
  pipeline: 'Pipeline',
};

function tokensOf(group: SnippetTokenGroup): Promise<TokenField[]> {
  if (group !== 'ticket') return customTokensOf(group);
  return listCustomProperties({ objectType: 'ticket' }).then(
    (defs) =>
      defs
        .filter((d) => !d.archived)
        .map((d) => ({ name: d.name, label: d.label }))
        .sort((a, b) => a.label.localeCompare(b.label)),
    // A business without Tickets: only the three ticket fields above.
    () => [],
  );
}

type Pop = 'more' | 'link' | 'personalize' | null;
type MorePop = 'font' | 'size' | 'color' | 'hilite' | 'align' | null;

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="field">
      <span className="field__label">{label}</span>
      {children}
    </div>
  );
}

export function SnippetEditorModal({
  snippet,
  all,
  folder,
  folders,
  shareOptions,
  onClose,
  onSaved,
}: {
  /** null: a new snippet. */
  snippet: Snippet | null;
  /** Every snippet, for the shortcut check. */
  all: Snippet[];
  /** Where a new snippet goes (the open folder). */
  folder: string | null;
  folders: SnippetFolder[];
  shareOptions: ShareOptions;
  onClose: () => void;
  onSaved: (saved: Snippet, created: boolean) => void;
}) {
  const toast = useToast();
  const [name, setName] = useState(snippet?.name ?? '');
  const [shortcut, setShortcut] = useState(snippet?.shortcut ?? '');
  const [hasText, setHasText] = useState(false);
  const [length, setLength] = useState(0);
  /** The saved text: one already over the limit can keep it. */
  const [savedText] = useState(() => snippetText(snippet?.bodyHtml ?? ''));
  const [inFolder, setInFolder] = useState(snippet ? (snippet.folder ?? '') : (folder ?? ''));
  // The design's new snippets are "Shared with everyone".
  const [share, setShare] = useState<ShareState>(() =>
    snippet ? shareOf(snippet.visibility, snippet.grants) : shareOf('shared'),
  );
  const [shareDrawer, setShareDrawer] = useState(false);
  const readOnly = Boolean(snippet && !snippet.canEdit);
  const canWrite = canWriteSnippets(useCurrentUser());
  const [saving, setSaving] = useState(false);
  /* Go-live QA: what stops a save shows in the dialog. A toast here covered Save and Cancel. */
  const [saveError, setSaveError] = useState('');
  /** The shortcut the API said is taken (by a snippet this list doesn't have). */
  const [refused, setRefused] = useState('');
  const [helpOpen, setHelpOpen] = useState(false);
  const bodyRef = useRef<HTMLDivElement>(null);
  const saved = useRef<Range | null>(null);
  const [pop, setPop] = useState<Pop>(null);
  const [morePop, setMorePop] = useState<MorePop>(null);
  const btns = useRef<Record<string, HTMLButtonElement | null>>({});
  const [, force] = useState(0);
  const anchor = (k: string) => btns.current[k] ?? null;
  const setBtn = (k: string) => (el: HTMLButtonElement | null) => {
    btns.current[k] = el;
  };
  const [fontName, setFontName] = useState('Sans Serif');
  const [fontSize, setFontSize] = useState('11');

  const plain = () =>
    (bodyRef.current?.innerText || bodyRef.current?.textContent || '').replace(/​/g, '').trim();
  const check = () => {
    setHasText(!!plain());
    setLength([...snippetText(bodyRef.current?.innerHTML ?? '')].length);
  };

  useEffect(() => {
    // The API sanitizes the body when it is saved.
    if (bodyRef.current) bodyRef.current.innerHTML = snippet?.bodyHtml ?? '';
    check();
    force((n) => n + 1); // anchors are set now
    // Filled once, when it opens.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const over =
    length > SNIPPET_MAX_CHARS && snippetText(bodyRef.current?.innerHTML ?? '') !== savedText;
  // A saved shortcut left as it is stays savable, as an over-long saved text does.
  const scError =
    readOnly || shortcut === snippet?.shortcut
      ? ''
      : shortcut === refused
        ? SHORTCUT_TAKEN
        : shortcutError(shortcut, all, snippet?.id);
  const valid = !readOnly && !!name.trim() && hasText && !!shortcut.trim() && !scError && !over;

  const selectionSave = () => {
    const sel = window.getSelection();
    const body = bodyRef.current;
    if (body && sel && sel.rangeCount) {
      const range = sel.getRangeAt(0);
      if (body.contains(range.commonAncestorContainer)) saved.current = range.cloneRange();
    }
  };
  const selectionRestore = () => {
    const body = bodyRef.current;
    if (!body) return;
    body.focus();
    const sel = window.getSelection();
    if (!sel) return;
    sel.removeAllRanges();
    if (saved.current && body.contains(saved.current.commonAncestorContainer)) {
      sel.addRange(saved.current);
    } else {
      const r = document.createRange();
      r.selectNodeContents(body);
      r.collapse(false);
      sel.addRange(r);
    }
  };
  const exec = (cmd: string, value?: string) => {
    selectionRestore();
    let colorRange: Range | null = null;
    if (cmd === 'foreColor') {
      const s = window.getSelection();
      if (s && s.rangeCount) colorRange = s.getRangeAt(0).cloneRange();
    }
    try {
      document.execCommand(cmd, false, value);
    } catch {
      // unsupported command
    }
    // Keep list markers the selected text's color (the design's linked list marker color).
    if (cmd === 'foreColor' && value && colorRange && bodyRef.current) {
      bodyRef.current.querySelectorAll('li').forEach((li) => {
        let touches = false;
        try {
          touches = colorRange.intersectsNode(li);
        } catch {
          touches = li.contains(colorRange.startContainer) || li.contains(colorRange.endContainer);
        }
        if (touches) {
          li.style.color = value;
          li.style.setProperty('--mt-marker-color', value);
        }
      });
    }
    selectionSave();
    check();
  };
  const insertNode = (node: Node) => {
    selectionRestore();
    const sel = window.getSelection();
    if (!sel || !sel.rangeCount) return;
    const range = sel.getRangeAt(0);
    range.deleteContents();
    range.insertNode(node);
    range.setStartAfter(node);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    selectionSave();
    check();
  };

  const toggle = (p: Exclude<Pop, null>) => {
    selectionSave();
    setMorePop(null);
    setPop((cur) => (cur === p ? null : p));
  };
  const toggleMore = (p: Exclude<MorePop, null>) => setMorePop((cur) => (cur === p ? null : p));
  const keepCaret = (e: React.MouseEvent) => {
    if ((e.target as Element).closest('button')) e.preventDefault();
  };

  const save = async () => {
    if (!valid || saving) return;
    const sc = shortcut.trim();
    setSaveError('');
    const bodyHtml = bodyRef.current?.innerHTML ?? '';
    setSaving(true);
    const body = {
      name: name.trim(),
      shortcut: sc,
      bodyHtml,
      folder: inFolder || null,
      ...shareToApi(share),
    };
    try {
      const out = snippet ? await updateSnippet(snippet.id, body) : await createSnippet(body);
      onSaved(out, !snippet);
    } catch (err) {
      if (isApiError(err) && err.isConflict && isShortcutRefusal(err.details)) {
        setRefused(shortcut);
        document.getElementById('snShortcut')?.focus();
      } else {
        // `details` names the {{field}} that is wrong; the message alone does not.
        const why = (isApiError(err) ? (err.details ?? []) : []).flatMap((d) => {
          const message = (d as { message?: unknown } | null)?.message;
          return typeof message === 'string' ? [message] : [];
        });
        setSaveError(why.length ? `${errorText(err)}: ${why.join('; ')}` : errorText(err));
      }
      setSaving(false);
    }
  };

  return (
    <MtModal
      id="mSnippet"
      onClose={onClose}
      labelledBy="snTitle"
      className="mt-snippet-modal"
      staticBackdrop
      focus="#snName"
    >
      <MtModalHead
        id="snTitle"
        title={readOnly ? 'View snippet' : snippet ? 'Edit snippet' : 'New snippet'}
        onClose={onClose}
      />
      <div className="mt-modal__body mt-snippet-body">
        <p className="mt-snippet-intro">
          Snippets allow you to create reusable blocks of text that you can access quickly through
          keyboard shortcuts. Get started by entering a phrase or line of text that you find
          yourself typing often, like a greeting or meeting agenda.{' '}
          <button
            type="button"
            className="link mt-snippet-learn"
            aria-expanded={helpOpen}
            aria-controls="snHelp"
            onClick={() => setHelpOpen((o) => !o)}
          >
            {helpOpen ? 'Show less.' : 'Learn more.'}
          </button>
        </p>
        {/* The CRM has no help site, so the help is here (go-live QA: the link went nowhere). */}
        <ul className="mt-snippet-more" id="snHelp" hidden={!helpOpen}>
          <li>
            <strong>Use it:</strong> type # and the shortcut, then Space or Enter, in a note, email,
            task, call, meeting or Inbox box. Or use that box&apos;s Insert snippet button.
          </li>
          <li>
            <strong>Personalize it:</strong> Personalize adds a field such as the contact&apos;s
            first name. Add a fallback value for records that don&apos;t have it. With neither, the
            gap shows in [brackets] for you to replace.
          </li>
          <li>
            <strong>Share it:</strong> choose who can use it under &quot;Who can use this
            snippet&quot;.
          </li>
          <li>
            <strong>Limits:</strong> up to {SNIPPET_MAX_CHARS.toLocaleString('en-US')} characters of
            text in each snippet.
          </li>
        </ul>
        <div className="field">
          <label className="field__label" htmlFor="snName">
            Internal name *
          </label>
          <input
            className="input"
            id="snName"
            type="text"
            maxLength={150}
            placeholder="Give your snippet a name"
            autoComplete="off"
            value={name}
            readOnly={readOnly}
            onChange={(e) => setName(e.target.value)}
          />
        </div>
        <div className="field">
          <label className="field__label" htmlFor="snContent">
            Snippet text *
          </label>
          <div className="mt-snippet-editor-wrap">
            <div
              ref={bodyRef}
              className="mt-editor mt-snippet-editor"
              id="snContent"
              contentEditable={!readOnly}
              suppressContentEditableWarning
              aria-readonly={readOnly}
              role="textbox"
              aria-multiline="true"
              data-mt-placeholder="Add the content of your snippet"
              onInput={check}
              onKeyUp={selectionSave}
              onMouseUp={selectionSave}
              onBlur={selectionSave}
            />
            <div
              className="mt-fmt mt-snippet-toolbar"
              role="toolbar"
              aria-label="Snippet formatting"
              hidden={readOnly}
            >
              {(
                [
                  ['bold', 'Bold', 'bold'],
                  ['italic', 'Italic', 'italic'],
                  ['underline', 'Underline', 'underline'],
                  ['removeFormat', 'Clear formatting', 'clear-format'],
                ] as const
              ).map(([cmd, label, icon]) => (
                <button
                  key={cmd}
                  type="button"
                  className="mt-fmt__btn"
                  aria-label={label}
                  title={label}
                  onMouseDown={(e) => e.preventDefault()}
                  onClick={() => exec(cmd)}
                >
                  <MtIcon name={icon} />
                </button>
              ))}
              <button
                ref={setBtn('more')}
                type="button"
                className="mt-fmt__txt"
                id="snMore"
                aria-haspopup="dialog"
                aria-expanded={pop === 'more'}
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => toggle('more')}
              >
                More
                <MtIcon name="chevron-down" size={14} />
              </button>
              <button
                ref={setBtn('link')}
                type="button"
                className="mt-fmt__btn"
                id="snLink"
                aria-label="Insert link"
                title="Insert link"
                aria-expanded={pop === 'link'}
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => toggle('link')}
              >
                <MtIcon name="link" />
              </button>
              <button
                ref={setBtn('personalize')}
                type="button"
                className="mt-fmt__txt"
                id="snPersonalize"
                aria-haspopup="dialog"
                aria-expanded={pop === 'personalize'}
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => toggle('personalize')}
              >
                Personalize
                <MtIcon name="chevron-down" size={14} />
              </button>
            </div>
          </div>
        </div>
        <p
          className={over ? 'mt-snippet-count is-over' : 'mt-snippet-count'}
          id="snCount"
          aria-live="polite"
        >
          {fmtNum(length)} of {fmtNum(SNIPPET_MAX_CHARS)} characters used
          {over ? '. Shorten the text to save it.' : ''}
        </p>
        <div className="field">
          <label className="field__label" htmlFor="snShortcut">
            Shortcut *
          </label>
          <p className="mt-snippet-help">
            To use a snippet, type the # symbol followed by the snippet shortcut you enter above.
            The snippet will then appear in the text editor.
          </p>
          <div className="mt-snippet-shortcut">
            <span>#</span>
            <input
              className="input"
              id="snShortcut"
              type="text"
              maxLength={40}
              placeholder="Type a word to use as a shortcut"
              autoComplete="off"
              aria-invalid={Boolean(scError)}
              aria-describedby={scError ? 'snShortcutError' : undefined}
              value={shortcut}
              readOnly={readOnly}
              onChange={(e) => {
                setShortcut(normalizeShortcut(e.target.value));
                setSaveError('');
              }}
            />
          </div>
          {scError ? (
            <p className="mt-field-error" id="snShortcutError" role="alert">
              {scError}
            </p>
          ) : null}
        </div>
        <div className="field">
          <span className="field__label">Folder</span>
          <MtSelect
            value={inFolder}
            searchable
            options={[
              { value: '', label: 'No folder' },
              ...folders.map((f) => ({ value: f.name, label: f.name })),
            ]}
            onChange={setInFolder}
          />
        </div>
        <div className="field">
          <span className="field__label">Who can use this snippet</span>
          <MtSelect
            value={share.mode}
            options={[
              { value: 'private', label: 'Private', sub: 'Only you can view and use it' },
              {
                value: 'everyone',
                label: 'Shared with everyone',
                sub: 'Everyone can view and use it',
              },
              {
                value: 'specific',
                label:
                  share.mode === 'specific'
                    ? shareLabel(share)
                    : 'Shared with specific users and teams',
                sub: 'Only the users and teams you choose',
              },
            ]}
            onChange={(mode) => {
              if (mode === 'specific') setShareDrawer(true);
              else setShare({ mode: mode as ShareState['mode'], users: [], teams: [] });
            }}
          />
        </div>
        {readOnly ? (
          <p className="mt-snippet-help">
            {canWrite
              ? 'Only its owner or a settings admin can change this snippet.'
              : 'You can view and insert snippets. Your permissions don’t include changing them.'}
          </p>
        ) : null}
      </div>
      <div className="mt-modal__foot mt-snippet-foot">
        {saveError ? (
          <p className="mt-field-error mt-snippet-foot__error" role="alert">
            {saveError}
          </p>
        ) : null}
        <button
          type="button"
          className="btn-crm btn-crm--primary"
          id="snSave"
          disabled={!valid || saving}
          onClick={() => void save()}
        >
          Save snippet
        </button>
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
      </div>

      {shareDrawer ? (
        <ShareDrawer
          noun="snippet"
          share={share.mode === 'specific' ? share : { mode: 'specific', users: [], teams: [] }}
          options={shareOptions}
          onClose={() => setShareDrawer(false)}
          onSave={(next) => {
            setShare(next);
            setShareDrawer(false);
          }}
        />
      ) : null}

      {pop === 'more' ? (
        <MtPop
          anchor={anchor('more')}
          onClose={() => {
            setPop(null);
            setMorePop(null);
          }}
          role="toolbar"
          label="More formatting"
        >
          <div className="mt-moretools" onMouseDown={keepCaret}>
            <button
              ref={setBtn('font')}
              type="button"
              className="mt-fmt__txt"
              aria-haspopup="listbox"
              aria-expanded={morePop === 'font'}
              onClick={() => toggleMore('font')}
            >
              <span>{fontName}</span>
              <MtIcon name="chevron-down" size={14} />
            </button>
            <button
              ref={setBtn('size')}
              type="button"
              className="mt-fmt__txt"
              aria-haspopup="listbox"
              aria-expanded={morePop === 'size'}
              onClick={() => toggleMore('size')}
            >
              <span>{fontSize}</span>
              <MtIcon name="chevron-down" size={14} />
            </button>
            <span className="mt-moretools__sep" />
            <button
              ref={setBtn('color')}
              type="button"
              className="mt-fmt__txt"
              aria-label="Text color"
              aria-haspopup="dialog"
              aria-expanded={morePop === 'color'}
              onClick={() => toggleMore('color')}
            >
              <MtIcon name="font-color" />
              <MtIcon name="chevron-down" size={14} />
            </button>
            <button
              ref={setBtn('hilite')}
              type="button"
              className="mt-fmt__txt"
              aria-label="Highlight color"
              aria-haspopup="dialog"
              aria-expanded={morePop === 'hilite'}
              onClick={() => toggleMore('hilite')}
            >
              <MtIcon name="highlight" />
              <MtIcon name="chevron-down" size={14} />
            </button>
            <span className="mt-moretools__sep" />
            <button
              type="button"
              className="mt-fmt__btn"
              aria-label="Bulleted list"
              onClick={() => exec('insertUnorderedList')}
            >
              <MtIcon name="list-bullets" />
            </button>
            <button
              type="button"
              className="mt-fmt__btn"
              aria-label="Numbered list"
              onClick={() => exec('insertOrderedList')}
            >
              <MtIcon name="list-ordered" />
            </button>
            <button
              ref={setBtn('align')}
              type="button"
              className="mt-fmt__txt"
              aria-label="Alignment"
              aria-haspopup="menu"
              aria-expanded={morePop === 'align'}
              onClick={() => toggleMore('align')}
            >
              <MtIcon name="align-left" />
              <MtIcon name="chevron-down" size={14} />
            </button>
          </div>
        </MtPop>
      ) : null}
      {pop === 'more' && morePop === 'font' ? (
        <MtPop anchor={anchor('font')} onClose={() => setMorePop(null)} arrow={false}>
          <MtListbox
            items={FONTS.map(([label, value]) => ({ value, label }))}
            selected={null}
            width={190}
            onSelect={(it) => {
              setMorePop(null);
              setFontName(it.label);
              exec('fontName', it.value);
            }}
          />
        </MtPop>
      ) : null}
      {pop === 'more' && morePop === 'size' ? (
        <MtPop anchor={anchor('size')} onClose={() => setMorePop(null)} arrow={false}>
          <MtListbox
            items={SIZES.map((v) => ({ value: v, label: v }))}
            selected={fontSize}
            width={90}
            onSelect={(it) => {
              setMorePop(null);
              setFontSize(it.value);
              exec('fontSize', SIZE_CMD[it.value] ?? '3');
            }}
          />
        </MtPop>
      ) : null}
      {pop === 'more' && (morePop === 'color' || morePop === 'hilite') ? (
        <MtPop anchor={anchor(morePop)} onClose={() => setMorePop(null)} arrow={false}>
          <div
            className="mt-swatches"
            role="group"
            aria-label={morePop === 'color' ? 'Text colors' : 'Highlight colors'}
          >
            {SWATCHES.map((c) => (
              <button
                key={c}
                type="button"
                className="mt-swatch"
                style={{ background: c }}
                aria-label={c}
                title={c}
                onMouseDown={(e) => e.preventDefault()}
                onClick={() => {
                  const cmd = morePop === 'color' ? 'foreColor' : 'hiliteColor';
                  setMorePop(null);
                  exec(cmd, c);
                }}
              />
            ))}
          </div>
        </MtPop>
      ) : null}
      {pop === 'more' && morePop === 'align' ? (
        <MtPop anchor={anchor('align')} onClose={() => setMorePop(null)}>
          <MtMenu
            onClose={() => setMorePop(null)}
            items={[
              { label: 'Align left', onClick: () => exec('justifyLeft') },
              { label: 'Align center', onClick: () => exec('justifyCenter') },
              { label: 'Align right', onClick: () => exec('justifyRight') },
            ]}
          />
        </MtPop>
      ) : null}

      {pop === 'link' ? (
        <MtPop anchor={anchor('link')} onClose={() => setPop(null)}>
          <LinkPanel
            onCancel={() => setPop(null)}
            onApply={(text, href, newTab) => {
              const a = document.createElement('a');
              a.href = href;
              a.target = newTab ? '_blank' : '_self';
              if (newTab) a.rel = 'noopener noreferrer';
              a.textContent = text || href;
              setPop(null);
              insertNode(a);
            }}
            invalid={() => toast('Enter a valid web address.', 'danger')}
          />
        </MtPop>
      ) : null}

      {pop === 'personalize' ? (
        <MtPop anchor={anchor('personalize')} onClose={() => setPop(null)}>
          <div className="mt-panel__body" style={{ width: 370 }}>
            <h3>Insert personalization token</h3>
            <TokenForm
              onCancel={() => setPop(null)}
              onSubmit={(group, field, fallback) => {
                const token = document.createElement('span');
                token.className = 'mt-token';
                token.setAttribute('data-type', group);
                token.setAttribute('data-token', field);
                token.setAttribute('data-fallback', fallback);
                token.textContent = mergeToken(group, field, fallback);
                setPop(null);
                insertNode(token);
              }}
            />
          </div>
        </MtPop>
      ) : null}
    </MtModal>
  );
}

/** The design's "Create link" panel: Link text, URL, Open in new tab, Apply / Cancel. */
function LinkPanel({
  onApply,
  onCancel,
  invalid,
}: {
  onApply: (text: string, href: string, newTab: boolean) => void;
  onCancel: () => void;
  invalid: () => void;
}) {
  const [text, setText] = useState(() => window.getSelection()?.toString().trim() ?? '');
  const [url, setUrl] = useState('');
  const [newTab, setNewTab] = useState(true);
  return (
    <div className="mt-panel__body mt-snippet-link-pop" style={{ width: 330 }}>
      <h3>Create link</h3>
      <Field label="Link text">
        <input
          className="input"
          type="text"
          placeholder="Link text"
          value={text}
          onChange={(e) => setText(e.target.value)}
        />
      </Field>
      <Field label="URL">
        <input
          className="input"
          type="url"
          placeholder="https://"
          value={url}
          onChange={(e) => setUrl(e.target.value)}
        />
      </Field>
      <label className="check">
        <input type="checkbox" checked={newTab} onChange={(e) => setNewTab(e.target.checked)} />
        <span className="check__box" />
        Open in new tab
      </label>
      <div className="mt-panel__actions">
        <button
          type="button"
          className="btn-crm btn-crm--sm btn-crm--primary"
          onClick={() => {
            let href = url.trim();
            if (href && !/^https?:\/\//i.test(href)) href = `https://${href}`;
            if (!href || !/^https?:\/\/[^\s]+$/i.test(href)) {
              invalid();
              return;
            }
            onApply(text.trim(), href, newTab);
          }}
        >
          Apply
        </button>
        <button type="button" className="btn-crm btn-crm--sm btn-crm--outline" onClick={onCancel}>
          Cancel
        </button>
      </div>
    </div>
  );
}

/**
 * The design's token form (snippets.js tokenForm): Type, Token (searchable), Fallback value,
 * Insert / Cancel. The fallback is used when the record has no value for the token.
 */
function TokenForm({
  onSubmit,
  onCancel,
}: {
  onSubmit: (group: SnippetTokenGroup, field: string, fallback: string) => void;
  onCancel: () => void;
}) {
  const [group, setGroup] = useState<SnippetTokenGroup>('contact');
  const [token, setToken] = useState<string | null>(null);
  const [fallback, setFallback] = useState('');
  const [custom, setCustom] = useState<TokenField[]>([]);
  useEffect(() => {
    let alive = true;
    setCustom([]);
    void tokensOf(group).then((fields) => {
      if (alive) setCustom(fields);
    });
    return () => {
      alive = false;
    };
  }, [group]);
  const g = SNIPPET_TOKEN_GROUPS.find((x) => x.key === group)!;
  const standard = g.fields as readonly string[];
  const options = [
    ...standard.map((f) => ({
      value: f,
      label: group === 'ticket' ? TICKET_LABELS[f]! : fieldLabel(f),
    })),
    ...custom
      .filter((c) => !standard.includes(c.name))
      .map((c) => ({ value: c.name, label: c.label })),
  ];
  return (
    <div className="mt-panel__body">
      <Field label="Type">
        <MtSelect
          value={group}
          options={SNIPPET_TOKEN_GROUPS.map((x) => ({ value: x.key, label: x.label }))}
          onChange={(v) => {
            setGroup(v as SnippetTokenGroup);
            setToken(null);
          }}
        />
      </Field>
      <Field label="Token">
        <MtSelect
          value={token}
          options={options}
          searchable
          placeholder={`Search ${g.label.toLowerCase()} tokens`}
          onChange={setToken}
        />
      </Field>
      <div className="field">
        <label className="field__label" htmlFor="snTokenFallback">
          Fallback value
        </label>
        <input
          className="input"
          id="snTokenFallback"
          type="text"
          placeholder="Enter fallback value (optional)"
          maxLength={200}
          autoComplete="off"
          value={fallback}
          onChange={(e) => setFallback(e.target.value)}
        />
        <p className="field__hint">Used when the record has no value for this token</p>
      </div>
      <div className="mt-panel__actions">
        <button
          type="button"
          className="btn-crm btn-crm--sm btn-crm--primary"
          disabled={!token}
          onClick={() => token && onSubmit(group, token, fallback.trim())}
        >
          Insert
        </button>
        <button type="button" className="btn-crm btn-crm--sm btn-crm--outline" onClick={onCancel}>
          Cancel
        </button>
      </div>
    </div>
  );
}
