'use client';

/**
 * Data Model > object > Conditional logic (HUB-355), as in the design's subLogic / subLogicList /
 * openLogicEditor: rules that show (and can require) dependent fields only while a controlling
 * field has chosen values. The create drawers, edit drawers and record sidebars apply them.
 */
import { useCallback, useEffect, useMemo, useState } from 'react';
import { createPortal } from 'react-dom';
import { useToast } from '@/components/crm/ToastProvider';
import type { CustomPropertyDefinition } from '@/features/custom-properties/api.client';
import {
  builtInLogicFields,
  canBeDependent,
  createPropertyLogic,
  deletePropertyLogic,
  listPropertyLogic,
  propertyLogicMatches,
  updatePropertyLogic,
  type PropertyLogicBody,
  type PropertyLogicOperator,
  type PropertyLogicRule,
} from '@/features/custom-properties/logic';
import { useOwners } from '@/features/owners/useOwners';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { errorText } from '@/lib/api/errors';
import { byText, customProperties, type DataModel, type DmObject } from '../model';
import { logicUpdatedText } from '../zoneText';
import { DmIcon } from './icons';
import { ColumnChooser } from '@/features/list-page/ui/ColumnChooser';
import {
  LOGIC_SET,
  MAX_FROZEN,
  orderColumns,
  readColumnPrefs,
  saveColumnPrefs,
  type ColumnPrefs,
} from '../manageColumns';
import {
  ActionMenu,
  CheckFilter,
  DataTable,
  Modal,
  SearchBox,
  SelectMenu,
  type Column,
} from './primitives';
import { lockItem, lockProps } from './viewOnly';

const OPERATORS: Array<{ value: PropertyLogicOperator; label: string }> = [
  { value: 'eq', label: 'is equal to' },
  { value: 'neq', label: 'is not equal to' },
  { value: 'any', label: 'is any of' },
  { value: 'none', label: 'is none of' },
  { value: 'known', label: 'is known' },
];
/** The editor's rule: no operator chosen yet on a new one. */
type LogicDraft = Omit<PropertyLogicBody, 'operator'> & { operator: PropertyLogicOperator | '' };

const operatorLabel = (op: PropertyLogicOperator) =>
  OPERATORS.find((o) => o.value === op)?.label ?? op;

type ControlKind = 'options' | 'user' | 'date';

/** Fields that can control a rule (the API's list): dropdowns, checkboxes, CRM user, dates. */
function controlKind(def: CustomPropertyDefinition): ControlKind | null {
  if (def.type === 'select' || def.type === 'multiselect') return 'options';
  if (def.type === 'text' && def.fieldType === 'owner') return 'user';
  if (def.type === 'date' || def.type === 'datetime') return 'date';
  return null;
}

/** The values a controlling field can take, as [value, label]. */
function useChoices(def: CustomPropertyDefinition | undefined) {
  const kind = def ? controlKind(def) : null;
  const { owners } = useOwners(kind === 'user', true);
  return useMemo<Array<{ value: string; label: string }>>(() => {
    if (!def || !kind) return [];
    if (kind === 'user') return owners.map((o) => ({ value: o.userId, label: o.name }));
    if (kind === 'options')
      return (def.options ?? []).map((o) => ({ value: o.value, label: o.label }));
    return [];
  }, [def, kind, owners]);
}

/* ================================================================ section */

export function LogicSection({
  object: o,
  model,
  canEdit = true,
}: {
  object: DmObject;
  model: DataModel;
  /** Without Manage settings: rules are listed, but can't be created, edited or deleted. */
  canEdit?: boolean;
}) {
  const toast = useToast();
  const { timeZone } = useUserPrefs();
  // Built-in fields rules may name by HubSpot's name (Lead status, Deal stage…), as dropdowns.
  const [builtIns, setBuiltIns] = useState<CustomPropertyDefinition[]>([]);
  useEffect(() => {
    let live = true;
    builtInLogicFields(o.key).then(
      (list) => live && setBuiltIns(list),
      () => live && setBuiltIns([]),
    );
    return () => {
      live = false;
    };
  }, [o.key]);
  const props = useMemo(
    () => [...customProperties(model, o.key), ...builtIns].sort((a, b) => byText(a.label, b.label)),
    [model, o.key, builtIns],
  );
  const [rules, setRules] = useState<PropertyLogicRule[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState('');
  // The list's filters, as in HubSpot: controlling property, dependent property, created by.
  const [ctrlFilter, setCtrlFilter] = useState<string[]>([]);
  const [depFilter, setDepFilter] = useState<string[]>([]);
  const [byFilter, setByFilter] = useState<string[]>([]);
  /** null: closed; 'new'; or the rule being edited. */
  const [editing, setEditing] = useState<PropertyLogicRule | 'new' | null>(null);
  /** C16/C17: the rules the delete dialog is for (one from a row, or the ticked ones). */
  const [deleting, setDeleting] = useState<PropertyLogicRule[] | null>(null);
  /** C16: the ticked rules, by id. */
  const [picked, setPicked] = useState<Set<string>>(new Set());
  // C18: the design's Edit columns, as the other Data Model tables (DMG3).
  const [columns, setColumns] = useState<ColumnPrefs>({ ids: LOGIC_SET.defaults, frozen: 0 });
  const [editingColumns, setEditingColumns] = useState(false);
  useEffect(() => setColumns(readColumnPrefs(LOGIC_SET)), []);

  const load = useCallback(() => {
    listPropertyLogic(o.key).then(
      (data) => {
        setRules(data);
        setError(null);
      },
      (err) => setError(errorText(err)),
    );
  }, [o.key]);
  useEffect(load, [load]);

  const label = (name: string) => props.find((p) => p.name === name)?.label ?? name;

  if (error) return <p className="dm-muted">Couldn&apos;t load the logic: {error}</p>;
  if (!rules) return <p className="dm-muted">Loading…</p>;

  const editor = editing && (
    <LogicEditor
      object={o}
      props={props}
      rule={editing === 'new' ? null : editing}
      onClose={() => setEditing(null)}
      onSaved={() => {
        setEditing(null);
        load();
      }}
    />
  );
  // C17: the design's "Delete logic permanently?" (data-model.js:2234-2287).
  const confirmDelete = deleting && deleting.length > 0 && (
    <Modal
      title="Delete logic permanently?"
      okLabel="Delete"
      danger
      onClose={() => setDeleting(null)}
      onOk={async () => {
        const failed: string[] = [];
        for (const r of deleting) {
          try {
            await deletePropertyLogic(r);
          } catch (err) {
            failed.push(`${label(r.controllingProperty)} (${errorText(err)})`);
          }
        }
        setPicked(new Set());
        load();
        if (failed.length) {
          toast(`Not deleted: ${failed.join(', ')}`, 'danger');
          return false;
        }
        toast('Logic deleted', 'success');
      }}
    >
      {deleting.length === 1 ? (
        <div className="dm-delete-logic-body">
          <p className="dm-delete-logic-intro">You&rsquo;re about to delete logic for:</p>
          <div className="dm-delete-logic-details">
            <div className="dm-delete-logic-ctrl">{label(deleting[0]!.controllingProperty)}</div>
            <div className="dm-delete-logic-cond">
              <ConditionText
                rule={deleting[0]!}
                def={props.find((p) => p.name === deleting[0]!.controllingProperty)}
              />
            </div>
            <div className="dm-delete-logic-deps">
              Show: {deleting[0]!.dependents.map((d) => label(d.name)).join(', ')}
            </div>
          </div>
          <p className="dm-delete-logic-warning">Are you sure? This can&rsquo;t be undone.</p>
        </div>
      ) : (
        <div className="dm-delete-logic-body">
          <p className="dm-delete-logic-intro">
            You&rsquo;re about to delete logic for <b>{deleting.length} rules</b>.
          </p>
          <p className="dm-delete-logic-warning">Are you sure? This can&rsquo;t be undone.</p>
        </div>
      )}
    </Modal>
  );

  if (!rules.length) {
    return (
      <>
        <div className="dm-logic">
          <div className="dm-logic__text">
            <h3>Make data entry easy</h3>
            <p>
              Get the data you need by showing the right properties at the right time. With
              Conditional Property Logic, you can show and require properties based on other
              properties.
            </p>
            <button
              type="button"
              className="dm-btn dm-btn--primary dm-btn--sm"
              onClick={() => setEditing('new')}
              {...lockProps(canEdit)}
            >
              Create logic
            </button>
          </div>
          <svg className="dm-logic__art" viewBox="0 0 360 230" aria-hidden="true">
            <g className="f">
              <rect x="10" y="70" width="86" height="96" rx="6" />
              <rect x="132" y="10" width="86" height="96" rx="6" />
              <rect x="132" y="124" width="86" height="96" rx="6" />
              <rect x="258" y="10" width="86" height="96" rx="6" />
              <rect x="258" y="124" width="86" height="96" rx="6" />
            </g>
            <g className="b">
              <rect x="22" y="96" width="62" height="16" rx="3" />
              <rect x="22" y="120" width="62" height="16" rx="3" />
              <rect x="144" y="36" width="62" height="16" rx="3" />
              <rect x="144" y="60" width="62" height="16" rx="3" className="o" />
              <rect x="144" y="150" width="62" height="16" rx="3" className="o" />
              <rect x="144" y="174" width="62" height="16" rx="3" />
            </g>
            <g className="l">
              <path d="M96 110 132 44M96 128l36 54M218 44h40M218 182h40" />
            </g>
            <g className="lines">
              <path d="M270 40h50M270 56h62M270 72h62M270 88h40M270 154h50M270 170h62M270 186h62M270 202h40" />
            </g>
          </svg>
        </div>
        {editor}
      </>
    );
  }

  const q = search.trim().toLowerCase();
  // C19: the design's "All users" is who last saved the rule (data-model.js:2061, 2452).
  const saverKey = (r: PropertyLogicRule) => r.updatedBy?.id ?? '';
  const rows = rules
    .map((r) => ({ rule: r, ctrl: label(r.controllingProperty) }))
    .filter(
      (x) =>
        (!q || x.ctrl.toLowerCase().includes(q)) &&
        (!ctrlFilter.length || ctrlFilter.includes(x.rule.controllingProperty)) &&
        (!depFilter.length || x.rule.dependents.some((d) => depFilter.includes(d.name))) &&
        (!byFilter.length || byFilter.includes(saverKey(x.rule))),
    );
  const optionsOf = (names: string[]) =>
    [...new Set(names)]
      .map((n) => ({ value: n, label: label(n) }))
      .sort((a, b) => byText(a.label, b.label));
  // C19: the design lists every property that can control logic, and every property as a
  // dependent, not only those used (data-model.js:2118-2135).
  const ctrlOptions = optionsOf([
    ...rules.map((r) => r.controllingProperty),
    ...props.filter((p) => controlKind(p)).map((p) => p.name),
  ]);
  const depOptions = optionsOf([
    ...rules.flatMap((r) => r.dependents.map((d) => d.name)),
    ...props.filter((p) => canBeDependent(o.key, p.name)).map((p) => p.name),
  ]);
  const saverOptions = [
    ...new Map(
      rules.map((r) => [
        saverKey(r),
        r.updatedBy?.name ?? (r.updatedBy ? 'Former user' : 'Unknown'),
      ]),
    ),
  ]
    .map(([value, text]) => ({ value, label: text }))
    .sort((a, b) => byText(a.label, b.label));
  const filtered = Boolean(q || ctrlFilter.length || depFilter.length || byFilter.length);
  const pickedRules = rows.filter((x) => picked.has(x.rule.id)).map((x) => x.rule);
  const pick = (id: string, on: boolean) =>
    setPicked((cur) => {
      const next = new Set(cur);
      if (on) next.add(id);
      else next.delete(id);
      return next;
    });
  const shown = columns.ids.length;
  const pickCol = {
    key: 'pick',
    label: (
      <input
        type="checkbox"
        aria-label="Select all logic"
        checked={pickedRules.length > 0}
        onChange={(e) =>
          setPicked(e.target.checked ? new Set(rows.map((x) => x.rule.id)) : new Set())
        }
      />
    ),
    width: '48px',
    render: (x: (typeof rows)[number]) => (
      <input
        type="checkbox"
        aria-label={`Select logic for ${x.ctrl}`}
        checked={picked.has(x.rule.id)}
        onChange={(e) => pick(x.rule.id, e.target.checked)}
      />
    ),
  };

  return (
    <>
      {/* The design's two rows (data-model.js:2152-2176). */}
      <div className="dm-toolbar dm-toolbar--rows">
        <div className="dm-toolbar__top">
          <SearchBox
            value={search}
            onChange={setSearch}
            placeholder="Search for a controlling property"
            wide
          />
          <span className="dm-grow" />
          <button
            type="button"
            className="dm-btn dm-btn--primary dm-btn--sm"
            onClick={() => setEditing('new')}
            {...lockProps(canEdit)}
          >
            <DmIcon name="plus" size={14} />
            Create logic
          </button>
          <button
            type="button"
            className="dm-btn dm-btn--outline dm-btn--sm"
            onClick={() => setEditingColumns(true)}
          >
            <DmIcon name="columns" size={14} />
            Edit columns
          </button>
        </div>
        <div className="dm-toolbar__filters dm-toolbar__filters--logic">
          <CheckFilter
            label={
              ctrlFilter.length
                ? `(${ctrlFilter.length}) Controlling properties`
                : 'All controlling properties'
            }
            options={ctrlOptions}
            selected={ctrlFilter}
            onChange={setCtrlFilter}
            search
          />
          <CheckFilter
            label={
              depFilter.length
                ? `(${depFilter.length}) Dependent properties`
                : 'All dependent properties'
            }
            options={depOptions}
            selected={depFilter}
            onChange={setDepFilter}
            search
          />
          <CheckFilter
            label={byFilter.length ? `(${byFilter.length}) Users` : 'All users'}
            options={saverOptions}
            selected={byFilter}
            onChange={setByFilter}
          />
        </div>
      </div>
      <DataTable
        rows={rows}
        rowKey={(x) => x.rule.id}
        sortKey="ctrl"
        frozen={columns.frozen ? columns.frozen + 1 : 0}
        rowCls={(x) => (picked.has(x.rule.id) ? 'is-selected' : undefined)}
        empty={filtered ? 'No logic matches your filters.' : 'No logic yet.'}
        // C16: the design's bulk header while rules are ticked (data-model.js:2080-2096).
        head={
          pickedRules.length > 0 ? (
            <tr>
              <th style={{ width: '48px' }}>
                <input
                  type="checkbox"
                  aria-label="Clear selection"
                  checked
                  onChange={() => setPicked(new Set())}
                />
              </th>
              <th colSpan={shown} className="dm-th--bulk">
                <div className="dm-lbulk-header">
                  <span className="dm-lbulk-count">{pickedRules.length} selected</span>
                  <button
                    type="button"
                    className="dm-lbulk-delete-btn"
                    onClick={() => setDeleting(pickedRules)}
                    {...lockProps(canEdit)}
                  >
                    <DmIcon name="trash" size={14} />
                    <span>Delete</span>
                  </button>
                </div>
              </th>
            </tr>
          ) : undefined
        }
        cols={[
          pickCol,
          ...orderColumns<Column<(typeof rows)[number]>>(
            [
              {
                key: 'ctrl',
                label: 'Controlling property',
                sort: true,
                width: '28%',
                render: (x) => (
                  <div className="dm-prop-cell">
                    {/* The editor has no read-only mode: the name is text for a view-only user. */}
                    {canEdit ? (
                      <button
                        type="button"
                        className="dm-plain-link dm-link-strong"
                        onClick={() => setEditing(x.rule)}
                      >
                        {x.ctrl}
                      </button>
                    ) : (
                      <span className="dm-link-strong">{x.ctrl}</span>
                    )}
                    {x.rule.active === false ? (
                      <span
                        className="dm-chip dm-chip--sm dm-chip--faint"
                        title="Its controlling property is archived, so the rule is skipped and its dependent properties always show"
                      >
                        Inactive
                      </span>
                    ) : null}
                    {/* C20: only the "..." menu, as the 20 Nov design (data-model.js:2030-2032). */}
                    <span className="dm-rowtools">
                      <ActionMenu
                        label={
                          <>
                            <DmIcon name="more-h" size={14} />
                            <span className="crm-visually-hidden">Actions for {x.ctrl}</span>
                          </>
                        }
                        btnClass="dm-icon-btn dm-icon-btn--xs dm-icon-btn--ring"
                        items={[
                          lockItem(
                            { label: 'Edit', icon: 'pencil', onClick: () => setEditing(x.rule) },
                            canEdit,
                          ),
                          lockItem(
                            {
                              label: 'Delete',
                              icon: 'trash',
                              onClick: () => setDeleting([x.rule]),
                            },
                            canEdit,
                          ),
                        ]}
                      />
                    </span>
                  </div>
                ),
              },
              {
                key: 'cond',
                label: 'Condition',
                render: (x) => (
                  <ConditionText
                    rule={x.rule}
                    def={props.find((p) => p.name === x.rule.controllingProperty)}
                  />
                ),
              },
              {
                key: 'deps',
                label: 'Dependent properties',
                sort: true,
                val: (x) => x.rule.dependents.length,
                render: (x) => (
                  <span className="dm-chips">
                    {x.rule.dependents.map((d) => (
                      <span key={d.name} className="dm-chip">
                        {label(d.name)}
                        {d.required ? ' *' : ''}
                      </span>
                    ))}
                  </span>
                ),
              },
              {
                key: 'updated',
                label: 'Last updated',
                sort: true,
                val: (x) => x.rule.updatedAt,
                render: (x) => logicUpdatedText(x.rule.updatedAt, x.rule.updatedBy?.name, timeZone),
              },
              {
                // C18: the design's optional "Dependent count" (data-model.js:2050-2055).
                key: 'count',
                label: 'Dependent count',
                sort: true,
                width: '15%',
                val: (x) => x.rule.dependents.length,
                render: (x) => String(x.rule.dependents.length),
              },
            ],
            columns.ids,
          ),
        ]}
      />
      <ColumnChooser
        open={editingColumns}
        columns={LOGIC_SET.columns}
        selected={columns.ids}
        lockedId={LOGIC_SET.locked}
        frozen={columns.frozen}
        maxFrozen={MAX_FROZEN}
        createHref={null}
        okLabel="Save"
        onClose={() => setEditingColumns(false)}
        onApply={(ids, frozen) => {
          const next = { ids, frozen };
          setColumns(next);
          saveColumnPrefs(LOGIC_SET, next);
          toast('Columns updated', 'success');
        }}
      />
      {editor}
      {confirmDelete}
    </>
  );
}

function ConditionText({
  rule,
  def,
}: {
  rule: PropertyLogicRule;
  def: CustomPropertyDefinition | undefined;
}) {
  const choices = useChoices(def);
  const names = rule.values.map((v) => choices.find((c) => c.value === v)?.label ?? v);
  return (
    <>
      {operatorLabel(rule.operator)}
      {rule.operator === 'known' ? '' : ` ${names.join(', ')}`}
    </>
  );
}

/* ================================================================ editor */

function LogicEditor({
  object: o,
  props,
  rule,
  onClose,
  onSaved,
}: {
  object: DmObject;
  props: CustomPropertyDefinition[];
  rule: PropertyLogicRule | null;
  onClose: () => void;
  onSaved: () => void;
}) {
  const toast = useToast();
  // A new rule starts with no operator ("Choose an operator"), as in the design.
  const [draft, setDraft] = useState<LogicDraft>(
    rule
      ? {
          controllingProperty: rule.controllingProperty,
          operator: rule.operator,
          values: [...rule.values],
          dependents: rule.dependents.map((d) => ({ ...d })),
        }
      : { controllingProperty: '', operator: '', values: [], dependents: [] },
  );
  const [dirty, setDirty] = useState(false);
  const [confirmClose, setConfirmClose] = useState(false);
  const [preview, setPreview] = useState('');
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    document.body.classList.add('dm-no-scroll');
    return () => document.body.classList.remove('dm-no-scroll');
  }, []);

  const change = (next: Partial<LogicDraft>) => {
    setDraft((d) => ({ ...d, ...next }));
    setDirty(true);
  };

  const ctrlDef = props.find((p) => p.name === draft.controllingProperty);
  const kind = ctrlDef ? controlKind(ctrlDef) : null;
  const choices = useChoices(ctrlDef);
  const operators = kind === 'date' ? OPERATORS.filter((op) => op.value === 'known') : OPERATORS;
  const multi = draft.operator === 'any' || draft.operator === 'none';
  const supported = props.filter((p) => controlKind(p));
  // Required fields can't be dependents: hidden, they'd still be demanded on create (the rule's
  // own "Required" is the way to require a dependent).
  const dependentOptions = props.filter(
    (p) => p.name !== draft.controllingProperty && !p.required && canBeDependent(o.key, p.name),
  );

  const valid =
    !!ctrlDef &&
    !!kind &&
    draft.operator !== '' &&
    (draft.operator === 'known'
      ? true
      : multi
        ? draft.values.length > 0
        : draft.values.length === 1) &&
    draft.dependents.length > 0 &&
    draft.dependents.every((d) => d.name);

  const save = async () => {
    if (!valid || draft.operator === '') return;
    setBusy(true);
    const body: PropertyLogicBody = {
      ...draft,
      operator: draft.operator,
      values: draft.operator === 'known' ? [] : draft.values,
    };
    try {
      if (rule) await updatePropertyLogic(rule, body);
      else await createPropertyLogic(o.key, body);
      toast('Logic saved', 'success');
      onSaved();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const cancel = () => (dirty ? setConfirmClose(true) : onClose());
  const moveDep = (i: number, by: number) => {
    const next = [...draft.dependents];
    const [d] = next.splice(i, 1);
    next.splice(i + by, 0, d!);
    change({ dependents: next });
  };

  // Preview: what the record form shows for a chosen controlling value.
  const previewShown =
    ctrlDef &&
    draft.operator &&
    propertyLogicMatches({ ...draft, operator: draft.operator }, preview)
      ? draft.dependents.filter((d) => d.name)
      : [];

  return createPortal(
    <div className="dm-pe dm-lg" role="dialog" aria-modal="true" aria-label="Edit property logic">
      <header className="dm-pe__bar">
        <span className="dm-pe__bar-side" aria-hidden="true" />
        <div className="dm-pe__title">
          <h2>Edit property logic</h2>
          <span>Object: {o.singular}</span>
        </div>
        <div className="dm-pe__acts">
          <button type="button" className="dm-pe__btn" onClick={cancel}>
            Cancel
          </button>
          <button
            type="button"
            className="dm-pe__btn dm-pe__btn--solid"
            disabled={!valid || busy || (rule !== null && !dirty)}
            onClick={() => void save()}
          >
            Save logic
          </button>
        </div>
      </header>
      <div className="dm-lg__main">
        <section className="dm-lg__edit" aria-label="Edit logic">
          <h3 className="dm-lg__h">Edit logic</h3>
          <p className="dm-lg__p">
            Property logic allows you to show and require properties based on the value in another
            property.
          </p>
          <h4 className="dm-lg__h">Controlling property</h4>
          <p className="dm-lg__p">When this is true:</p>
          <div className="dm-lg__stack">
            <SelectMenu
              value={draft.controllingProperty}
              // C21: the design's Supported / Unsupported headings (data-model.js:2382-2383).
              options={[
                ...supported.map((p) => ({ value: p.name, label: p.label, group: 'Supported' })),
                ...props
                  .filter((p) => !controlKind(p))
                  .map((p) => ({
                    value: p.name,
                    label: p.label,
                    group: 'Unsupported',
                    disabled: true,
                    title: "This field type can't control logic",
                  })),
              ]}
              placeholder="Choose a property"
              search
              ariaLabel="Controlling property"
              onChange={(name) => {
                const def = props.find((p) => p.name === name);
                change({
                  controllingProperty: name,
                  operator: def && controlKind(def) === 'date' ? 'known' : draft.operator,
                  values: [],
                  dependents: draft.dependents.filter((d) => d.name !== name),
                });
                setPreview('');
              }}
            />
            <SelectMenu
              value={draft.operator}
              options={operators}
              placeholder="Choose an operator"
              ariaLabel="Operator"
              disabled={!ctrlDef}
              onChange={(operator) =>
                change({
                  operator,
                  values:
                    operator === 'known'
                      ? []
                      : operator === 'eq' || operator === 'neq'
                        ? draft.values.slice(0, 1)
                        : draft.values,
                })
              }
            />
            {/* The option picker shows from the start, locked until an operator is chosen. */}
            {draft.operator === 'known' ? null : multi ? (
              <CheckFilter
                label={
                  draft.values.length
                    ? draft.values
                        .map((v) => choices.find((c) => c.value === v)?.label ?? v)
                        .join(', ')
                    : 'Choose options'
                }
                options={choices}
                selected={draft.values}
                onChange={(values) => change({ values })}
                search={choices.length > 6}
                wide
                className="dm-lg__multi"
              />
            ) : (
              <SelectMenu
                value={draft.values[0] ?? ''}
                options={choices}
                placeholder="Choose an option"
                search={choices.length > 8}
                ariaLabel="Option"
                disabled={!ctrlDef || draft.operator === ''}
                onChange={(v) => change({ values: [v] })}
              />
            )}
          </div>
          <div className="dm-lg__div" />
          <h4 className="dm-lg__h">Dependent properties ({draft.dependents.length})</h4>
          {draft.dependents.length ? (
            <p className="dm-lg__p">Show these properties:</p>
          ) : (
            <p className="dm-lg__p">No dependent properties</p>
          )}
          {draft.dependents.map((d, i) => {
            const taken = new Set(draft.dependents.map((x) => x.name));
            const items = dependentOptions
              .filter((p) => p.name === d.name || !taken.has(p.name))
              .map((p) => ({ value: p.name, label: p.label }));
            const set = (next: Partial<{ name: string; required: boolean }>) =>
              change({
                dependents: draft.dependents.map((x, j) => (j === i ? { ...x, ...next } : x)),
              });
            return (
              <div key={i} className="dm-lg__dep">
                <div className="dm-lg__move">
                  <button
                    type="button"
                    aria-label="Move up"
                    disabled={i === 0}
                    onClick={() => moveDep(i, -1)}
                  >
                    <DmIcon name="chevron-up" size={13} />
                  </button>
                  <button
                    type="button"
                    aria-label="Move down"
                    disabled={i === draft.dependents.length - 1}
                    onClick={() => moveDep(i, 1)}
                  >
                    <DmIcon name="chevron-down" size={13} />
                  </button>
                </div>
                <div className="dm-lg__depmain">
                  <div className="dm-lg__dephead">
                    <b>Property</b>
                    <span className="dm-grow" />
                    <label className="dm-lg__req">
                      <input
                        type="checkbox"
                        checked={d.required}
                        onChange={(e) => set({ required: e.target.checked })}
                      />
                      Required
                    </label>
                    <button
                      type="button"
                      className="dm-link-strong dm-lg__rm"
                      onClick={() =>
                        change({ dependents: draft.dependents.filter((_, j) => j !== i) })
                      }
                    >
                      <DmIcon name="trash" size={13} />
                      Remove
                    </button>
                  </div>
                  <SelectMenu
                    value={d.name}
                    options={items}
                    placeholder="Choose a property"
                    search
                    ariaLabel={`Dependent property ${i + 1}`}
                    onChange={(name) => set({ name })}
                  />
                </div>
              </div>
            );
          })}
          <button
            type="button"
            className="dm-btn dm-btn--outline dm-btn--xs dm-lg__add"
            disabled={draft.dependents.length >= 50}
            onClick={() =>
              change({ dependents: [...draft.dependents, { name: '', required: false }] })
            }
          >
            <DmIcon name="plus" size={13} />
            Add property
          </button>
        </section>

        <section className="dm-lg__preview" aria-label="Preview logic">
          <h3 className="dm-lg__h">Preview logic</h3>
          <div className="dm-lg__pv">
            <span className="dm-lg__pvlabel">{ctrlDef?.label ?? 'Controlling property'}</span>
            {kind === 'date' ? (
              <input
                className="dm-input"
                type="date"
                value={preview}
                aria-label="Preview value"
                onChange={(e) => setPreview(e.target.value)}
              />
            ) : (
              <SelectMenu
                value={preview}
                options={[{ value: '', label: '--' }, ...choices]}
                placeholder="--"
                ariaLabel="Preview value"
                disabled={!ctrlDef}
                onChange={setPreview}
              />
            )}
            <div className={`dm-lg__pvcard${draft.dependents.length && ctrlDef ? 'has-deps' : ''}`}>
              {!ctrlDef ? (
                <p>Your dependent properties will appear here</p>
              ) : !previewShown.length ? (
                <p>No dependent properties exist for this choice</p>
              ) : (
                previewShown.map((d) => {
                  const dp = props.find((p) => p.name === d.name);
                  if (!dp) return null;
                  return (
                    <div key={d.name} className="dm-lg__pvfield">
                      <span className="dm-lg__pvlabel">
                        {dp.label}
                        {d.required ? <i className="dm-lg__star"> *</i> : null}
                      </span>
                      <PreviewControl def={dp} />
                    </div>
                  );
                })
              )}
            </div>
          </div>
        </section>
      </div>
      {confirmClose && (
        <Modal
          title="Are you sure you want to cancel?"
          okLabel="Close without saving"
          cancelLabel="Back to editing"
          onClose={() => setConfirmClose(false)}
          onOk={() => onClose()}
        >
          <p className="dm-muted">Any changes made to this form will not be saved.</p>
        </Modal>
      )}
    </div>,
    document.body,
  );
}

/** An empty input of the field's kind, for the preview only. */
function PreviewControl({ def }: { def: CustomPropertyDefinition }) {
  if (def.type === 'select' || def.type === 'multiselect' || def.fieldType === 'owner')
    return (
      <div className="dm-select">
        <button type="button" className="dm-select__btn" tabIndex={-1}>
          <span />
          <DmIcon name="caret" size={18} />
        </button>
      </div>
    );
  if (def.type === 'boolean')
    return (
      <label className="dm-check dm-check--plain">
        <input type="checkbox" />
        <span>Yes</span>
      </label>
    );
  if (def.type === 'textarea')
    return <textarea className="dm-textarea" rows={2} aria-label={def.label} />;
  if (def.type === 'date' || def.type === 'datetime')
    return <input className="dm-input" type="date" aria-label={def.label} />;
  if (def.type === 'number')
    return <input className="dm-input" type="number" aria-label={def.label} />;
  return <input className="dm-input" type="text" aria-label={def.label} />;
}
