'use client';

import { useEffect, useMemo, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { createCustomProperty, type PropertyType } from '@/features/custom-properties/api.client';
import {
  activateCrmDefinedObject,
  createObjectDefinition,
  listCrmDefinedObjects,
} from '@/features/objects/api.client';
import type { CrmDefinedObject, ObjectDefinition } from '@/features/objects/types';
import { createPipeline } from '@/features/pipelines/api.client';
import {
  keyError,
  RESERVED_FIELD_NAMES,
  OBJECT_ICONS,
  recordNameField,
  toFieldName,
  toObjectKey,
} from '@/features/settings/ui/CustomObjectSettings';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { byText, CUSTOM_OBJECT_LIMIT, customObjectCount, type DataModel } from '../model';
import { nameClashFromError, objectNameClash, type NameClash } from '../objectNames';
import { linkable, presetAssociations } from '../createObjectPreset';
import { DmIcon } from './icons';
import { NameClashError } from './NameClashError';
import { Drawer, DrawerHead, Dropdown, SelectMenu, Tip } from './primitives';

/**
 * "Create a new object" (HUB-605), as in the design's createObjectDrawer: pick a CRM-defined
 * object (Appointments, Courses, Listings, Services) and confirm it, or build a custom object
 * with a description, a primary display property and secondary display properties. The AI
 * section is out of scope.
 */

type Step = { kind: 'list' } | { kind: 'crm'; key: string } | { kind: 'custom' };

/** Field types offered for display properties (no dropdown: it would need options first). */
const DISPLAY_TYPES: Array<{ value: PropertyType; label: string }> = [
  { value: 'text', label: 'Single-line text' },
  { value: 'number', label: 'Number' },
  { value: 'date', label: 'Date picker' },
  { value: 'datetime', label: 'Date and time picker' },
  { value: 'boolean', label: 'Single checkbox' },
];
const UNIQUE_TYPES: PropertyType[] = ['text', 'number'];
const MAX_SECONDARY = 10;

/** "Pet" -> "Pets", "Company" -> "Companies", "Box" -> "Boxes". */
export function pluralize(word: string): string {
  const s = word.trim();
  if (!s) return '';
  if (/[^aeiou]y$/i.test(s)) return `${s.slice(0, -1)}ies`;
  if (/(s|x|z|ch|sh)$/i.test(s)) return `${s}es`;
  return `${s}s`;
}

export function CreateObjectPanel({
  open,
  model,
  takenKeys,
  startKey,
  onClose,
  onCreated,
}: {
  open: boolean;
  model: DataModel;
  /** A CRM-defined object to open on (its Activate object): its confirm step, Back to the list. */
  startKey?: string | null;
  /** Keys of every object, archived included. */
  takenKeys: Set<string>;
  onClose: () => void;
  onCreated: (definition: ObjectDefinition) => void;
}) {
  const [step, setStep] = useState<Step>({ kind: 'list' });
  const [catalog, setCatalog] = useState<CrmDefinedObject[] | null>(null);
  const [catalogError, setCatalogError] = useState<string | null>(null);

  useEffect(() => {
    if (!open) return;
    setStep(startKey ? { kind: 'crm', key: startKey } : { kind: 'list' });
    setCatalog(null);
    setCatalogError(null);
    let live = true;
    listCrmDefinedObjects()
      .then((data) => live && setCatalog(data))
      .catch((err) => live && setCatalogError(errorText(err)));
    return () => {
      live = false;
    };
  }, [open, startKey]);

  const back = () => setStep({ kind: 'list' });
  const picked = step.kind === 'crm' ? catalog?.find((o) => o.key === step.key) : undefined;

  return (
    <Drawer open={open} onClose={onClose} label="Create a new object">
      <div className="dm-co">
        {step.kind === 'list' && (
          <ListStep
            model={model}
            catalog={catalog}
            catalogError={catalogError}
            onClose={onClose}
            onPick={(key) => setStep({ kind: 'crm', key })}
            onCustom={() => setStep({ kind: 'custom' })}
          />
        )}
        {step.kind === 'crm' && !picked && <p className="dm-muted">{catalogError ?? 'Loading…'}</p>}
        {step.kind === 'crm' && picked && (
          <ConfirmStep
            model={model}
            template={picked}
            onBack={back}
            onClose={onClose}
            onCreated={onCreated}
          />
        )}
        {step.kind === 'custom' && (
          <CustomStep
            model={model}
            takenKeys={takenKeys}
            onBack={back}
            onClose={onClose}
            onCreated={onCreated}
          />
        )}
      </div>
    </Drawer>
  );
}

/* ================================================================ step 1: list */

function ListStep({
  model,
  catalog,
  catalogError,
  onClose,
  onPick,
  onCustom,
}: {
  model: DataModel;
  catalog: CrmDefinedObject[] | null;
  catalogError: string | null;
  onClose: () => void;
  onPick: (key: string) => void;
  onCustom: () => void;
}) {
  const toast = useToast();
  const count = customObjectCount(model);
  const full = count >= CUSTOM_OBJECT_LIMIT;
  return (
    <>
      <DrawerHead title="Create a new object" onClose={onClose} />
      <div className="dm-drawer__body">
        <h3 className="dm-drawer__h3">Create manually</h3>
        <p className="dm-drawer__label">Choose a CRM-defined object</p>
        {catalogError && <p className="dm-muted">Couldn&apos;t load them: {catalogError}</p>}
        {!catalog && !catalogError && <p className="dm-muted">Loading…</p>}
        {catalog?.map((o) => (
          <button
            key={o.key}
            type="button"
            className={cn('dm-pick', o.object && 'is-done')}
            onClick={() =>
              o.object ? toast(`${o.object.pluralLabel} is already active.`) : onPick(o.key)
            }
          >
            <span className="dm-pick__title">
              <DmIcon name={o.icon} size={18} />
              {o.object?.pluralLabel ?? o.pluralLabel}
              {o.object && <span className="dm-badge dm-badge--success">Active</span>}
            </span>
            <span className="dm-pick__desc">{o.description}</span>
          </button>
        ))}
        <p className="dm-drawer__label">Or create a custom object</p>
        <button
          type="button"
          className="dm-pick"
          disabled={full}
          title={full ? `You can have at most ${CUSTOM_OBJECT_LIMIT} custom objects.` : undefined}
          onClick={onCustom}
        >
          <span className="dm-pick__title">
            <DmIcon name="grid" size={18} />
            Custom object
          </span>
          <span className="dm-pick__desc">Build your own object from scratch</span>
        </button>
        <p className="dm-drawer__note">
          {count} out of {CUSTOM_OBJECT_LIMIT} custom objects created
        </p>
      </div>
    </>
  );
}

/**
 * A7 (DMG13): "Create association" as the design's chips (coTags, data-model.js:558-575):
 * activities locked (always linked), the chosen objects with ×, and a searchable menu to add
 * the rest. Objects this CRM keeps no records of can't be linked, so they aren't offered.
 */
function AssociationPicker({
  model,
  selected,
  onChange,
}: {
  model: DataModel;
  selected: string[];
  onChange: (next: string[]) => void;
}) {
  const [q, setQ] = useState('');
  const activities = model.objects
    .filter((o) => o.active && o.activity)
    .sort((a, b) => byText(a.name, b.name));
  const nameOf = (key: string) => model.objects.find((o) => o.key === key)?.name ?? key;
  const rest = model.objects
    .filter((o) => linkable(o) && !selected.includes(o.key))
    .sort((a, b) => byText(a.name, b.name));
  const shown = rest.filter(
    (o) => !q.trim() || o.name.toLowerCase().includes(q.trim().toLowerCase()),
  );
  return (
    <>
      <h3 className="dm-co__h">
        Create association <DmIcon name="info" size={13} />
      </h3>
      <p className="dm-co__p">Select the objects you want to associate to</p>
      <div className="dm-co-tags">
        {activities.map((a) => (
          <span
            key={a.key}
            className="dm-co-tag is-locked"
            title="Activities can always be associated"
          >
            {a.name}
          </span>
        ))}
        {selected.map((k) => (
          <span key={k} className="dm-co-tag">
            {nameOf(k)}
            <button
              type="button"
              aria-label={`Remove ${nameOf(k)}`}
              onClick={() => onChange(selected.filter((x) => x !== k))}
            >
              <DmIcon name="x" size={12} />
            </button>
          </span>
        ))}
        <Dropdown
          className="dm-co-tags__dd"
          btnClass="dm-icon-btn"
          menuClass="dm-menu dm-menu--select"
          role="listbox"
          right
          ariaLabel="Add association"
          label={<DmIcon name="caret" size={18} />}
        >
          {(close) => (
            <>
              <label className="dm-pop__search">
                <input
                  type="search"
                  placeholder="Search"
                  aria-label="Search objects"
                  value={q}
                  autoFocus
                  onChange={(e) => setQ(e.target.value)}
                />
                <DmIcon name="search" />
              </label>
              {shown.map((o) => (
                <button
                  key={o.key}
                  type="button"
                  role="option"
                  aria-selected={false}
                  className="dm-menu__item"
                  onClick={() => {
                    close();
                    setQ('');
                    onChange([...selected, o.key]);
                  }}
                >
                  <span>{o.name}</span>
                </button>
              ))}
              {!rest.length ? (
                <p className="dm-pop__empty">All objects selected</p>
              ) : !shown.length ? (
                <p className="dm-pop__empty">No results</p>
              ) : null}
            </>
          )}
        </Dropdown>
      </div>
    </>
  );
}

/**
 * A8 (DMG13): the design's internal name (coInternal, data-model.js:576-580): shown as text with
 * a pencil that opens the box.
 */
function InternalName({
  value,
  onEdit,
  label,
}: {
  value: string;
  onEdit: (v: string) => void;
  label: string;
}) {
  const [editing, setEditing] = useState(false);
  return (
    <p className="dm-co-internal">
      Internal name <DmIcon name="info" size={13} />:{' '}
      {editing ? (
        <input
          className="dm-input dm-input--sm"
          type="text"
          value={value}
          maxLength={64}
          aria-label={label}
          autoFocus
          onChange={(e) => onEdit(e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, '_'))}
        />
      ) : (
        <>
          <span>{value}</span>
          <button
            type="button"
            className="dm-icon-btn dm-icon-btn--xs"
            aria-label={`Edit ${label.toLowerCase()}`}
            onClick={() => setEditing(true)}
          >
            <DmIcon name="pencil" size={13} />
          </button>
        </>
      )}
    </p>
  );
}

/* ================================================================ step 2a: CRM-defined */

function ConfirmStep({
  model,
  template,
  onBack,
  onClose,
  onCreated,
}: {
  model: DataModel;
  template: CrmDefinedObject;
  onBack: () => void;
  onClose: () => void;
  onCreated: (definition: ObjectDefinition) => void;
}) {
  const toast = useToast();
  const [singular, setSingular] = useState(template.singularLabel);
  const [edited, setEdited] = useState<Record<string, string>>({});
  const [associated, setAssociated] = useState<string[]>(() =>
    presetAssociations(model.objects, template.key),
  );
  const [busy, setBusy] = useState(false);
  const name = singular.trim();
  const isDefault = name === template.singularLabel;
  const plural = isDefault ? template.pluralLabel : pluralize(name);
  // #561: renamed to a name another object uses (the template itself left out, as the API).
  const [serverClash, setServerClash] = useState<NameClash | null>(null);
  const nameClash =
    objectNameClash(model.objects, { singular: name, plural }, template.key) ?? serverClash;
  // Field labels follow the new name unless edited ("Appointment Name" -> "Visit Name").
  const labelOf = (f: { name: string; label: string }) =>
    edited[f.name] ??
    (isDefault || !name ? f.label : f.label.replace(template.singularLabel, name));

  const activate = async () => {
    setBusy(true);
    try {
      const fieldLabels = Object.fromEntries(
        template.fields
          .map((f) => [f.name, labelOf(f).trim()] as const)
          .filter(([n, l]) => l && l !== template.fields.find((f) => f.name === n)!.label),
      );
      const created = await activateCrmDefinedObject(template.key, {
        ...(isDefault ? {} : { singularLabel: name, pluralLabel: plural }),
        ...(Object.keys(fieldLabels).length ? { fieldLabels } : {}),
        associatedTypes: associated,
      });
      toast(`${created.pluralLabel} object activated`, 'success');
      onCreated(created);
    } catch (err) {
      const clash = nameClashFromError(err);
      if (clash) setServerClash(clash);
      else toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  return (
    <>
      <DrawerHead title="Confirm object details" onClose={onClose} onBack={onBack} />
      <div className="dm-drawer__body">
        <p className="dm-co__lead">Make adjustments as needed</p>
        <label className="dm-field">
          <span className="dm-field__label">Object name (Singular) *</span>
          <input
            className={cn('dm-input', (!name || nameClash?.field === 'singular') && 'is-invalid')}
            type="text"
            value={singular}
            maxLength={100}
            aria-invalid={!name || nameClash?.field === 'singular'}
            onChange={(e) => {
              setSingular(e.target.value);
              setServerClash(null);
            }}
          />
          <NameClashError clash={nameClash} field="singular" />
        </label>
        {!isDefault && (
          <button
            type="button"
            className="dm-link dm-co__reset"
            onClick={() => {
              setSingular(template.singularLabel);
              setEdited({});
              setServerClash(null);
            }}
          >
            Reset to default <DmIcon name="info" size={13} />
          </button>
        )}
        <label className="dm-field">
          <span className="dm-field__label">Object name (Plural) *</span>
          <input
            className={cn('dm-input', nameClash?.field === 'plural' && 'is-invalid')}
            type="text"
            value={plural}
            disabled
          />
          <NameClashError clash={nameClash} field="plural" />
        </label>
        <p className="dm-co-meta">
          Object type ID <DmIcon name="info" size={13} />:{' '}
          <strong>{template.hubspotObjectTypeId}</strong>
        </p>
        <label className="dm-field">
          <span className="dm-field__label">Description</span>
          <textarea className="dm-textarea" rows={3} value={template.description} disabled />
        </label>
        {template.fields.length > 0 && (
          <>
            <h3 className="dm-co__h">Properties</h3>
            <p className="dm-co__p">
              Relevant property labels will be adjusted to match the new object name (opt out is
              available).{' '}
              <Tip text="Change a replacement label to keep your own, or reset them all to the defaults." />
            </p>
            <button
              type="button"
              className="dm-link"
              disabled={!Object.keys(edited).length}
              onClick={() => setEdited({})}
            >
              Reset to default labels
            </button>
            <div className="dm-co-map">
              <table>
                <thead>
                  <tr>
                    <th>Object type</th>
                    <th>Current property</th>
                    <th aria-label="becomes" />
                    <th>Replacement property</th>
                  </tr>
                </thead>
                <tbody>
                  {template.fields.map((f) => (
                    <tr key={f.name}>
                      <td>{template.pluralLabel}</td>
                      <td>{f.label}</td>
                      <td className="dm-co-map__arrow">→</td>
                      <td>
                        <input
                          className="dm-input dm-input--sm"
                          type="text"
                          value={labelOf(f)}
                          maxLength={100}
                          aria-label={`Replacement for ${f.label}`}
                          onChange={(e) => setEdited((x) => ({ ...x, [f.name]: e.target.value }))}
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </>
        )}
        <div className="dm-co-info">
          <DmIcon name="info" size={16} />
          <p>
            You&apos;ll now see your new singular and plural object names and property labels in
            most areas of CRM. Some places, especially in Settings, may still show the original CRM
            default names. Internal names haven&apos;t changed and will stay the same.
          </p>
        </div>
        <AssociationPicker model={model} selected={associated} onChange={setAssociated} />
      </div>
      <div className="dm-drawer__foot">
        <button
          type="button"
          className={cn('dm-btn dm-btn--primary', busy && 'is-loading')}
          disabled={!name || Boolean(nameClash) || busy}
          onClick={() => void activate()}
        >
          Activate
        </button>
        <button type="button" className="dm-btn dm-btn--outline" onClick={onBack}>
          Cancel
        </button>
      </div>
    </>
  );
}

/* ================================================================ step 2b: custom object */

interface DisplayProp {
  label: string;
  /** Set when the internal name was typed by hand. */
  name: string | null;
  type: PropertyType;
}

function CustomStep({
  model,
  takenKeys,
  onBack,
  onClose,
  onCreated,
}: {
  model: DataModel;
  takenKeys: Set<string>;
  onBack: () => void;
  onClose: () => void;
  onCreated: (definition: ObjectDefinition) => void;
}) {
  const toast = useToast();
  const [singular, setSingular] = useState('');
  const [plural, setPlural] = useState<string | null>(null);
  const [key, setKey] = useState<string | null>(null);
  const [description, setDescription] = useState('');
  const [primary, setPrimary] = useState<DisplayProp>({ label: '', name: null, type: 'text' });
  const [unique, setUnique] = useState(false);
  const [secondary, setSecondary] = useState<DisplayProp[]>([]);
  const [icon, setIcon] = useState('');
  const [hasPipeline, setHasPipeline] = useState(false);
  const [associated, setAssociated] = useState<string[]>(() =>
    presetAssociations(model.objects, 'custom'),
  );
  const [busy, setBusy] = useState(false);
  // #561: the API's 409 for a used name (a stale model), until a name is typed again.
  const [serverClash, setServerClash] = useState<NameClash | null>(null);

  const shownPlural = plural ?? pluralize(singular);
  const shownKey = key ?? toObjectKey(shownPlural || singular);
  // #561: a name another object uses; the object whose key this one takes is left out (as the API).
  const nameClash =
    objectNameClash(model.objects, { singular, plural: shownPlural }, shownKey) ?? serverClash;
  const fieldName = (p: DisplayProp) =>
    p.name ?? (shownKey ? recordNameField(p.label, shownKey) : toFieldName(p.label));

  const problems = useMemo(() => {
    const out: string[] = [];
    // Always checked once a name is in: an emptied internal name is a problem too.
    if (shownKey || singular.trim()) {
      const k = keyError(shownKey, takenKeys);
      if (k) out.push(`Internal name: ${k}`);
    }
    const names = [primary, ...secondary].filter((p) => p.label.trim()).map(fieldName);
    if (new Set(names).size !== names.length)
      out.push('Each property needs its own internal name.');
    if (names.some((n) => !/^[a-z][a-z0-9_]{0,63}$/.test(n)))
      out.push('Property internal names use lowercase letters, digits and _.');
    // A typed name the API keeps for standard fields ("name", "email"): the field would be refused
    // after the object is created, leaving it without its record name field.
    const reserved = names.filter((n) => RESERVED_FIELD_NAMES.has(n));
    if (reserved.length)
      out.push(`"${reserved.join('", "')}" is a standard field name: pick another internal name.`);
    return out;
    // fieldName depends on shownKey only
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [shownKey, singular, takenKeys, primary, secondary]);

  const ready =
    singular.trim() &&
    shownPlural.trim() &&
    primary.label.trim() &&
    !problems.length &&
    !nameClash &&
    !busy;

  const create = async () => {
    setBusy(true);
    const singularLabel = singular.trim();
    const pluralLabel = shownPlural.trim();
    const groupName = `${singularLabel} information`;
    const secondaries = secondary.filter((p) => p.label.trim());
    let created: ObjectDefinition;
    try {
      created = await createObjectDefinition({
        key: shownKey,
        singularLabel,
        pluralLabel,
        displayProperty: fieldName(primary),
        icon: icon || null,
        hasPipeline,
        associatedTypes: associated,
        description: description.trim() || null,
        secondaryDisplayProperties: secondaries.map(fieldName),
      });
    } catch (err) {
      const clash = nameClashFromError(err);
      if (clash) setServerClash(clash);
      else toast(errorText(err), 'danger');
      setBusy(false);
      return;
    }
    // As in Settings > Objects: the object exists now; report what didn't get added.
    const unfinished: string[] = [];
    const fields = [
      { p: primary, unique: unique && UNIQUE_TYPES.includes(primary.type) },
      ...secondaries.map((p) => ({ p, unique: false })),
    ];
    for (const [i, { p, unique: isUnique }] of fields.entries()) {
      try {
        await createCustomProperty({
          objectType: shownKey,
          name: fieldName(p),
          label: p.label.trim(),
          type: p.type,
          unique: isUnique || undefined,
          groupName,
          displayOrder: i,
        });
      } catch (err) {
        unfinished.push(`its "${p.label.trim()}" property (${errorText(err)})`);
      }
    }
    if (hasPipeline) {
      try {
        await createPipeline({
          name: `${singularLabel} pipeline`,
          objectType: shownKey,
          stages: [
            { name: 'New', stageType: 'open', probability: 10 },
            { name: 'In progress', stageType: 'open', probability: 50 },
            { name: 'Done', stageType: 'won', probability: 100 },
            { name: 'Lost', stageType: 'lost', probability: 0 },
          ],
        });
      } catch (err) {
        unfinished.push(`its first pipeline (${errorText(err)})`);
      }
    }
    setBusy(false);
    toast(
      unfinished.length
        ? `${pluralLabel} was created, but not ${unfinished.join(' or ')}.`
        : `${singularLabel} object created`,
      unfinished.length ? 'danger' : 'success',
    );
    onCreated(created);
  };

  const typeSelect = (p: DisplayProp, set: (p: DisplayProp) => void, label: string) => (
    <SelectMenu
      value={p.type}
      options={DISPLAY_TYPES}
      onChange={(type) => set({ ...p, type })}
      ariaLabel={label}
    />
  );
  const internal = (value: string, onEdit: (v: string) => void, label: string) => (
    <InternalName value={value} onEdit={onEdit} label={label} />
  );

  return (
    <>
      <DrawerHead title="Create an object from scratch" onClose={onClose} onBack={onBack} />
      <div className="dm-drawer__body">
        <h3 className="dm-co__h dm-co__h--first">What do you want to call your object?</h3>
        <label className="dm-field">
          <span className="dm-field__label">Object name (Singular) *</span>
          <span className="dm-field__hint">Example: Pet</span>
          <input
            className={cn('dm-input', nameClash?.field === 'singular' && 'is-invalid')}
            type="text"
            value={singular}
            maxLength={100}
            autoFocus
            aria-invalid={nameClash?.field === 'singular'}
            onChange={(e) => {
              setSingular(e.target.value);
              setServerClash(null);
            }}
          />
          <NameClashError clash={nameClash} field="singular" />
        </label>
        <label className="dm-field">
          <span className="dm-field__label">Object name (Plural) *</span>
          <span className="dm-field__hint">Example: Pets</span>
          <input
            className={cn('dm-input', nameClash?.field === 'plural' && 'is-invalid')}
            type="text"
            value={shownPlural}
            maxLength={100}
            disabled={!singular.trim()}
            aria-invalid={nameClash?.field === 'plural'}
            onChange={(e) => {
              setPlural(e.target.value);
              setServerClash(null);
            }}
          />
          <NameClashError clash={nameClash} field="plural" />
        </label>
        {internal(
          shownKey,
          (v) => {
            setKey(v.slice(0, 32));
            // The name check leaves out the object whose key this one takes: check again.
            setServerClash(null);
          },
          'Object internal name',
        )}
        <label className="dm-field">
          <span className="dm-field__label">Description</span>
          <span className="dm-field__hint">
            The description gives people context about this object when they use it in CRM tools.
          </span>
          <textarea
            className="dm-textarea"
            rows={3}
            value={description}
            maxLength={2000}
            placeholder="Type your description"
            onChange={(e) => setDescription(e.target.value)}
          />
        </label>

        <h3 className="dm-co__h">Create primary display property</h3>
        <p className="dm-co__p">
          The primary display property is the property used to identify and name each record.{' '}
          <Tip text='For a "Pets" object, the primary display property could be "Pet name": each record is named after the pet.'>
            <span className="dm-link">See an example</span>
          </Tip>
        </p>
        <label className="dm-field">
          <span className="dm-field__label">Primary display property *</span>
          <span className="dm-field__hint">Example: Pet name</span>
          <input
            className="dm-input"
            type="text"
            value={primary.label}
            maxLength={191}
            placeholder="Create property"
            onChange={(e) => setPrimary({ ...primary, label: e.target.value })}
          />
        </label>
        {internal(
          fieldName(primary),
          (v) => setPrimary({ ...primary, name: v }),
          'Primary display property internal name',
        )}
        <div className="dm-field">
          <span className="dm-field__label">Property type *</span>
          {typeSelect(primary, setPrimary, 'Primary display property type')}
        </div>
        <label className="dm-check dm-check--plain">
          <input
            type="checkbox"
            checked={unique && UNIQUE_TYPES.includes(primary.type)}
            disabled={!UNIQUE_TYPES.includes(primary.type)}
            onChange={(e) => setUnique(e.target.checked)}
          />
          <span>Require unique values</span>
        </label>

        <h3 className="dm-co__h">Create secondary display properties</h3>
        <p className="dm-co__p">
          Secondary display properties appear just below the primary property. They add context to a
          record.{' '}
          <Tip text='For a "Pets" object, "Breed" and "Owner" could show under each pet name.'>
            <span className="dm-link">See an example</span>
          </Tip>
        </p>
        {secondary.map((s, i) => {
          const set = (next: DisplayProp) =>
            setSecondary((list) => list.map((x, j) => (j === i ? next : x)));
          return (
            <div key={i} className="dm-co-sec">
              <div className="dm-field">
                <span className="dm-field__label">Secondary display property</span>
                <span className="dm-field__row">
                  <input
                    className="dm-input"
                    type="text"
                    value={s.label}
                    maxLength={191}
                    placeholder="Create property"
                    aria-label={`Secondary display property ${i + 1}`}
                    onChange={(e) => set({ ...s, label: e.target.value })}
                  />
                  <button
                    type="button"
                    className="dm-icon-btn"
                    aria-label="Remove secondary property"
                    onClick={() => setSecondary((list) => list.filter((_, j) => j !== i))}
                  >
                    <DmIcon name="trash" size={16} />
                  </button>
                </span>
              </div>
              {internal(
                fieldName(s),
                (v) => set({ ...s, name: v }),
                `Secondary display property ${i + 1} internal name`,
              )}
              <div className="dm-field">
                <span className="dm-field__label">Property type *</span>
                {typeSelect(s, set, `Secondary display property ${i + 1} type`)}
              </div>
            </div>
          );
        })}
        {secondary.length < MAX_SECONDARY && (
          <button
            type="button"
            className="dm-link dm-co__add"
            onClick={() =>
              setSecondary((list) => [...list, { label: '', name: null, type: 'text' }])
            }
          >
            <DmIcon name="plus" size={14} />
            Add secondary property
          </button>
        )}

        <AssociationPicker model={model} selected={associated} onChange={setAssociated} />

        <h3 className="dm-co__h">More options</h3>
        <div className="dm-field">
          <span className="dm-field__label">Icon</span>
          <SelectMenu
            value={icon}
            options={[
              { value: '', label: 'None' },
              ...OBJECT_ICONS.map((o) => ({ value: o.value as string, label: o.label as string })),
            ]}
            onChange={setIcon}
            ariaLabel="Icon"
          />
        </div>
        <label className="dm-check dm-check--plain">
          <input
            type="checkbox"
            checked={hasPipeline}
            onChange={(e) => setHasPipeline(e.target.checked)}
          />
          <span>Records move through a pipeline (stages and a board)</span>
        </label>
        {problems.map((p) => (
          <p key={p} className="dm-co__p dm-pe__danger" role="alert">
            {p}
          </p>
        ))}
      </div>
      <div className="dm-drawer__foot">
        <button
          type="button"
          className={cn('dm-btn dm-btn--primary', busy && 'is-loading')}
          disabled={!ready}
          onClick={() => void create()}
        >
          Create
        </button>
        <button type="button" className="dm-btn dm-btn--outline" onClick={onBack}>
          Cancel
        </button>
      </div>
    </>
  );
}
