'use client';

import Link from 'next/link';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { useToast } from '@/components/crm/ToastProvider';
import { publicEnv } from '@/config/env';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { accessChoices, bulkAccessSummary } from '@/features/custom-properties/access-assignees';
import {
  accessBody,
  archiveCustomProperty,
  assigneesOf,
  deleteCustomProperty,
  isLockedField,
  listPropertyFillRates,
  PROPERTY_ACCESS_CHOICES,
  restoreCustomProperty,
  updateCustomProperty,
  type AccessAssignees,
  type CustomPropertyDefinition,
  type PropertyAccess,
} from '@/features/custom-properties/api.client';
import {
  listPropertyHistory,
  listPropertyUsage,
  listStandardPropertyHistory,
  loadDataModel,
  setStandardPropertyGroup,
} from '@/features/data-model/api.client';
import {
  downloadFile,
  fieldTypeLabel,
  groupLabel,
  isCrmProvided,
  liveGroups,
  propertyAssetCount,
  toCsv,
  type DataModel,
  type DmObject,
} from '@/features/data-model/model';
import type { PropertyUsage } from '@/features/data-model/api.client';
import { AccessAssigneesField, hasAssignees } from '@/features/data-model/ui/AccessAssigneesField';
import { CreatePropertyPanel } from '@/features/data-model/ui/CreatePropertyPanel';
import { LogicSection } from '@/features/data-model/ui/LogicSection';
import { canOpenProperty } from '@/features/data-model/ui/viewOnly';
import {
  PropertyEditor,
  type PropertyEditorMode,
  type PropertyEditorSection,
  type PropertySeed,
} from '@/features/data-model/ui/PropertyEditor';
import { listMembers } from '@/features/members/api.client';
import { listOwners } from '@/features/owners/api.client';
import {
  canEditPropertySettings,
  canOpenSettingsHref,
  isSuperAdmin,
  PROPERTY_SETTINGS_ONLY,
} from '@/features/permission-sets/property-settings';
import {
  creatorOf,
  isSystemCreator,
  loadMemberNames,
  userFilterItems,
  type Creator,
  type MemberName,
} from '../createdBy';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { mapLimited } from '@/lib/utils/map-limited';
import { byLabel, sortKey } from '@/lib/utils/sort-label';
import { deleteArchived, isDeletable, type DeleteOutcome } from '../archivedDelete';
import { trackChangesHref } from '../audit-scope';
import {
  exportFile,
  exportSheet,
  type ExportFile,
  type ExportFormat,
  type ExportSheet,
} from '../propertyExport';
import { useUserPrefs } from '../UserPrefs';
import { archivedDay, archivedTimeText } from './archivedTime';
import { ExportPropertiesDialog } from './ExportPropertiesDialog';
import { PropertyGroupsTab } from './PropertyGroupsTab';
import { Ico, ListPop, MenuPop, PpModal, type ListItem, type MenuItem } from './properties-ui';

/* ------------------------------------------------------------------- data */

type Tab = 'props' | 'logic' | 'groups' | 'archived';
const TABS: Tab[] = ['props', 'logic', 'groups', 'archived'];

/** The editor sections under the design's URL names (`&tab=` while the editor is open). */
const SECTION_PARAMS: Record<PropertyEditorSection, string> = {
  details: 'details',
  type: 'fieldType',
  docs: 'documentation',
  rules: 'rules',
  conditional: 'conditional',
  access: 'manageAccess',
  preview: 'preview',
  smart: 'smartProperties',
  autofill: 'autofill',
  usage: 'usedIn',
  quality: 'dataQuality',
  sources: 'dataSources',
};
const sectionOf = (param: string | null): PropertyEditorSection =>
  (Object.keys(SECTION_PARAMS) as PropertyEditorSection[]).find(
    (s) => SECTION_PARAMS[s] === param,
  ) ?? 'details';

/** Objects with Data Agent and Data Quality in the header, as the design. */
const DQ_OBJECTS = new Set(['contact', 'company']);
/** Objects with a page in Settings › Objects. */
const SETTINGS_OBJECTS = new Set(['contact', 'company', 'deal']);

const SMART = [
  ['on', 'Auto-fill on', 'Data Agent prompt set, autofill enabled'],
  ['off', 'Auto-fill off', 'Data Agent prompt set, autofill disabled'],
  ['none', 'Not a smart property', 'No Data Agent prompt set'],
] as const;
/**
 * The "All field types" filter, grouped as the design's $TYPE_GROUPS: every type is listed,
 * used or not. Currency, Percentage and Rollup aren't in the design; they go with Number.
 */
const TYPE_GROUPS: Array<[string, string[]]> = [
  ['Text input', ['Single-line text', 'Multi-line text', 'Phone number']],
  [
    'Choosing options',
    [
      'Single checkbox',
      'Multiple checkboxes',
      'Date picker',
      'Date and time picker',
      'Dropdown select',
      'Radio select',
    ],
  ],
  ['Values', ['Number', 'Currency', 'Percentage', 'Calculation', 'Rollup']],
  ['Other', ['Property sync', 'File', 'CRM user', 'Rich text', 'URL', 'Email']],
];
const PER_PAGE = [10, 25, 100];
const PER_KEY = 'crm.properties.per';

/** `?object=`: a key (contact) or the design's plural (contacts). */
function objectKeyOf(param: string | null, objects: DmObject[]): string | null {
  if (!param) return null;
  const v = param.toLowerCase();
  const found =
    objects.find((o) => o.key === v) ??
    objects.find((o) => o.typeId === v) ??
    objects.find((o) => o.name.toLowerCase() === v) ??
    objects.find((o) => `${o.key}s` === v || `${o.key.replace(/y$/, 'ie')}s` === v);
  return found?.key ?? null;
}

function accessLabel(p: CustomPropertyDefinition): string {
  const access = p.access === 'everyone_edit' && isLockedField(p) ? 'everyone_view' : p.access;
  return (
    PROPERTY_ACCESS_CHOICES.find((c) => c.value === access)?.short ??
    (isLockedField(p) ? 'Everyone can view' : 'Everyone can view and edit')
  );
}

/** A field's group by internal name; a built-in field's group is its label (or none). */
function groupNameOf(groups: Array<{ name: string; label: string }>, group: string | null) {
  if (!group) return '';
  return (
    (groups.find((g) => g.name === group) ?? groups.find((g) => g.label === group))?.name ?? group
  );
}

const fillText = (n: number | null) => (n === null ? '—' : `${Math.round(n * 100) / 100}%`);

/** Used In per field name. */
const usageMap = (rows: PropertyUsage[]) =>
  new Map(rows.map((r) => [r.name, propertyAssetCount(r)]));
/** Fill rate (percent) per field id. */
const fillMap = (rows: Array<{ id: string; filled: number; total: number }>) =>
  new Map(rows.map((r) => [r.id, r.total ? (r.filled / r.total) * 100 : 0]));

interface Row {
  p: CustomPropertyDefinition;
  label: string;
  type: string;
  access: string;
  group: string;
  /** The group's internal name: built-in fields carry its label, which may differ. */
  groupName: string;
  by: string;
  /** Created by: the filter uses its key, the table its label (`by`). */
  creator: Creator;
  used: number;
  /** Percent of records with a value; null when not known (built-in and activity fields). */
  fill: number | null;
}

type SortKey = 'label' | 'access' | 'group' | 'by' | 'used' | 'fill';
type Filters = { group: string; type: string; user: string; access: string; smart: string };
const NO_FILTERS: Filters = { group: '', type: '', user: '', access: '', smart: '' };

/* ------------------------------------------------------------------- view */

/**
 * Settings › Properties, as the design (settings-properties.php): object picker, the
 * Properties / Conditional logic / Groups / Archived tabs, filters, bulk actions and a sortable,
 * paged table. A property's name opens the full-page editor
 * (`?object=…&action=edit&property=<name>&tab=details`).
 */
export function PropertiesSettingsView() {
  const toast = useToast();
  const router = useRouter();
  const pathname = usePathname();
  const params = useSearchParams();
  const me = useCurrentUser();
  // Batch P1 (HubSpot): Edit property settings changes properties; deleting one for good and its
  // history stay with Super Admins, as the API does.
  const canManage = canEditPropertySettings(me);
  const superAdmin = isSuperAdmin(me);

  const [model, setModel] = useState<DataModel | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [members, setMembers] = useState<Map<string, MemberName>>(new Map());
  /** Every member's name loaded; until then (or when that fails) unknown ids aren't "removed". */
  const [membersComplete, setMembersComplete] = useState(false);
  const [membersNotice, setMembersNotice] = useState<string | null>(null);
  const [usage, setUsage] = useState<Map<string, number>>(new Map());
  const [fills, setFills] = useState<Map<string, number>>(new Map());

  const reload = useCallback(async () => {
    try {
      setModel(await loadDataModel());
      setError(null);
    } catch (err) {
      setError(errorText(err));
    }
  }, []);
  useEffect(() => {
    void reload();
    // Every member, page by page: a creator past the first page isn't a removed user. Batch P1:
    // only Super Admins list members (the API's `manage users`); anyone else with the page open
    // reads the owners list, which every member may (members of any status, by name).
    const page = superAdmin
      ? (cursor?: string) => listMembers({ limit: 200, cursor })
      : (cursor?: string) => listOwners({ limit: 200, cursor, includeDeactivated: true });
    void loadMemberNames(page, setMembers).then(({ complete, error: failed }) => {
      setMembersComplete(complete);
      if (complete) return;
      setMembersNotice(
        failed
          ? `Some users' names couldn't be loaded (${errorText(failed)}), so "Created by" shows them as Unknown user.`
          : 'This account has more users than can be listed here, so "Created by" shows some as Unknown user.',
      );
    });
  }, [reload, superAdmin]);

  const objects = useMemo(
    () =>
      (model?.objects ?? [])
        // Users have fields though no records (#261).
        .filter((o) => o.active && (!o.catalog || o.fieldOnly) && !o.deactivated)
        .sort((a, b) => a.name.localeCompare(b.name)),
    [model],
  );
  const objectKey = objectKeyOf(params.get('object'), objects) ?? 'contact';
  const object = objects.find((o) => o.key === objectKey) ?? null;
  const editorOpen = params.get('action') === 'edit' || params.get('action') === 'clone';
  const tabParam = editorOpen ? null : params.get('tab');
  const [tab, setTabState] = useState<Tab>(
    TABS.includes(tabParam as Tab) ? (tabParam as Tab) : 'props',
  );

  /** Replaces the query: the object, the tab (unless Properties) and any extras. */
  const syncUrl = useCallback(
    (next: { object?: string; tab?: Tab; extra?: Record<string, string> }) => {
      const q = new URLSearchParams();
      q.set('object', next.object ?? objectKey);
      const t = next.tab ?? tab;
      if (!next.extra && t !== 'props') q.set('tab', t);
      for (const [k, v] of Object.entries(next.extra ?? {})) q.set(k, v);
      router.replace(`${pathname}?${q.toString()}`, { scroll: false });
    },
    [objectKey, tab, pathname, router],
  );

  // Used In and Fill Rate of the object's fields.
  useEffect(() => {
    if (!object) return;
    let alive = true;
    listPropertyUsage(object.key).then(
      (rows) => alive && setUsage(usageMap(rows)),
      () => alive && setUsage(new Map()),
    );
    // No records to count: activities, and Users (the members hold their values).
    if (object.activity || object.fieldOnly) setFills(new Map());
    else {
      listPropertyFillRates(object.key).then(
        (rows) => alive && setFills(fillMap(rows)),
        () => alive && setFills(new Map()),
      );
    }
    return () => {
      alive = false;
    };
  }, [object, model?.loadedAt]);

  const all = useMemo(() => (model ? (model.properties[objectKey] ?? []) : []), [model, objectKey]);
  const live = useMemo(() => all.filter((p) => !p.archived), [all]);
  const archived = useMemo(() => all.filter((p) => p.archived), [all]);

  const creator = useCallback(
    (p: CustomPropertyDefinition) =>
      creatorOf(p, members, { crmProvided: isCrmProvided(p), membersComplete }),
    [members, membersComplete],
  );
  const byName = useCallback((p: CustomPropertyDefinition) => creator(p).label, [creator]);
  /** A member's name (or email), or the id when they aren't loaded. */
  const memberLabel = (id: string) => {
    const m = members.get(id);
    return m ? m.name || m.email : id;
  };
  const rows = useMemo<Row[]>(
    () =>
      live.map((p) => ({
        p,
        label: p.label,
        type: fieldTypeLabel(p),
        access: accessLabel(p),
        group: model ? groupLabel(model, objectKey, p.groupName) : '',
        groupName: groupNameOf(model?.groups[objectKey] ?? [], p.groupName),
        by: byName(p),
        creator: creator(p),
        used: usage.get(p.name) ?? 0,
        fill: fills.get(p.id) ?? null,
      })),
    [live, model, objectKey, byName, creator, usage, fills],
  );

  /* ---------------------------------------------------------- the editor */
  const [editor, setEditor] = useState<{
    mode: PropertyEditorMode;
    property: CustomPropertyDefinition | null;
    seed?: PropertySeed;
    section?: PropertyEditorSection;
  } | null>(null);
  const [creating, setCreating] = useState(false);

  const openEditor = (
    mode: PropertyEditorMode,
    property: CustomPropertyDefinition,
    section: PropertyEditorSection = 'details',
  ) => {
    setEditor({ mode, property, section });
    syncUrl({
      extra: { action: mode, property: property.name, tab: SECTION_PARAMS[section] },
    });
  };
  /** The field just closed: the URL keeps it until the navigation lands, so don't reopen it. */
  const closedProperty = useRef<string | null>(null);
  const closeEditor = () => {
    closedProperty.current = editor?.property?.name ?? null;
    setEditor(null);
    syncUrl({});
  };

  // A link with `action=edit&property=<name>` opens the editor once the fields are loaded.
  const urlProperty = editorOpen ? params.get('property') : null;
  useEffect(() => {
    if (urlProperty !== closedProperty.current) closedProperty.current = null;
    if (!model || editor || !urlProperty || closedProperty.current) return;
    const found = all.find((p) => p.name === urlProperty && !p.archived);
    const mode = params.get('action') === 'clone' ? 'clone' : 'edit';
    // Batch P1: without Edit property settings a saved field opens read-only; Clone writes.
    if (found && canOpenProperty(canManage, mode, true)) {
      setEditor({
        mode,
        property: found,
        section: sectionOf(params.get('tab')),
      });
    }
    // Only when the URL names another field.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [model, urlProperty]);

  /* ------------------------------------------------------ table state */
  const [q, setQ] = useState('');
  const [f, setF] = useState<Filters>(() => ({ ...NO_FILTERS, group: params.get('group') ?? '' }));
  const [sort, setSort] = useState<{ key: SortKey; dir: 'asc' | 'desc' }>({
    key: 'label',
    dir: 'asc',
  });
  const [page, setPage] = useState(1);
  const [per, setPer] = useState(10);
  const [sel, setSel] = useState<Set<string>>(new Set());
  const [pop, setPop] = useState<{ kind: string; anchor: HTMLElement; row?: Row } | null>(null);
  const closePop = useCallback(() => setPop(null), []);

  useEffect(() => {
    try {
      const saved = Number(localStorage.getItem(PER_KEY));
      if (PER_PAGE.includes(saved)) setPer(saved);
    } catch {
      /* no storage: 10 per page */
    }
  }, []);

  const setTab = (t: Tab) => {
    setTabState(t);
    syncUrl({ tab: t });
  };
  const setObject = (key: string) => {
    if (key === objectKey) return;
    setQ('');
    setF(NO_FILTERS);
    setPage(1);
    setSel(new Set());
    syncUrl({ object: key });
  };

  const filtered = useMemo(() => {
    const s = q.trim().toLowerCase();
    const out = rows.filter((r) => {
      if (s && !`${r.label} ${r.p.name} ${r.p.description ?? ''}`.toLowerCase().includes(s))
        return false;
      if (f.group && r.groupName !== f.group) return false;
      if (f.type && r.type !== f.type) return false;
      if (f.user === '__custom') {
        if (isSystemCreator(r.creator.key)) return false;
      } else if (f.user && r.creator.key !== f.user) return false;
      if (f.access && r.access !== f.access) return false;
      if (f.smart && f.smart !== 'none') return false;
      return true;
    });
    const d = sort.dir === 'asc' ? 1 : -1;
    return out.sort((a, b) => {
      const x = a[sort.key];
      const y = b[sort.key];
      if (sort.key === 'used' || sort.key === 'fill') {
        const n = (v: string | number | null) => (typeof v === 'number' ? v : -1);
        return (n(x) - n(y)) * d || byLabel(a.label, b.label);
      }
      return (
        sortKey(String(x)).localeCompare(sortKey(String(y)), undefined, {
          sensitivity: 'base',
          numeric: true,
        }) * d || byLabel(a.label, b.label)
      );
    });
  }, [rows, q, f, sort]);

  const pages = Math.max(1, Math.ceil(filtered.length / per));
  const current = Math.min(page, pages);
  const pageRows = filtered.slice((current - 1) * per, current * per);
  const selected = rows.filter((r) => sel.has(r.p.id));
  const anyFilter = Object.values(f).some(Boolean);

  const toggleSel = (id: string, on: boolean) =>
    setSel((cur) => {
      const next = new Set(cur);
      if (on) next.add(id);
      else next.delete(id);
      return next;
    });

  const filterItems = (k: keyof Filters): ListItem[] => {
    if (k === 'group') {
      return [
        { value: '', label: 'All groups' },
        ...(model ? liveGroups(model, objectKey) : [])
          .map((g) => ({ value: g.name, label: g.label }))
          .sort((a, b) => byLabel(a.label, b.label)),
      ];
    }
    if (k === 'type') {
      // A type outside the design's groups (one the CRM adds later) still shows, under Other.
      const listed = new Set(TYPE_GROUPS.flatMap(([, types]) => types));
      const extra = [...new Set(rows.map((r) => r.type))].filter((t) => !listed.has(t)).sort();
      return [
        { value: '', label: 'All field types' },
        ...TYPE_GROUPS.flatMap(([head, types]) => [
          { value: `__head:${head}`, label: head, heading: true },
          ...[...types, ...(head === 'Other' ? extra : [])].map((t) => ({
            value: t,
            label: t,
            indent: true,
          })),
        ]),
      ];
    }
    if (k === 'user') return userFilterItems(rows.map((r) => r.creator));
    if (k === 'access') {
      return [
        { value: '', label: 'All access' },
        // "Assigned" shows once it can be chosen, or while a field has it.
        ...accessChoices(
          publicEnv().NEXT_PUBLIC_ASSIGNED_ACCESS,
          live.some((p) => p.access === 'assigned') ? 'assigned' : null,
        ).map((c) => ({ value: c.short, label: c.short })),
      ];
    }
    return [
      { value: '', label: 'All properties' },
      ...SMART.map(([value, label, desc]) => ({ value, label, desc })),
    ];
  };
  const FILTERS: Array<[keyof Filters, string]> = [
    ['group', 'All groups'],
    ['type', 'All field types'],
    ['user', 'All users'],
    ['access', 'All access'],
    ['smart', 'All properties'],
  ];
  const filterLabel = (k: keyof Filters, allLabel: string) => {
    const v = f[k];
    if (!v) return allLabel;
    // The filter holds a creator's key; the chip shows its name.
    if (k === 'user') return filterItems('user').find((i) => i.value === v)?.label ?? v;
    if (k === 'smart') return SMART.find((s) => s[0] === v)?.[1] ?? v;
    if (k === 'group') return model ? groupLabel(model, objectKey, v) : v;
    return v;
  };

  /* ------------------------------------------------------------ actions */
  const [moving, setMoving] = useState<Row[] | null>(null);
  const [moveTo, setMoveTo] = useState('');
  const [accessOf, setAccessOf] = useState<Row[] | null>(null);
  const [accessTo, setAccessTo] = useState<PropertyAccess | ''>('');
  const [accessAssignees, setAccessAssignees] = useState<AccessAssignees>(assigneesOf(null));
  const [archiving, setArchiving] = useState<Row[] | null>(null);
  const [restoring, setRestoring] = useState<CustomPropertyDefinition[] | null>(null);
  const [deleting, setDeleting] = useState<CustomPropertyDefinition[] | null>(null);
  /** Why the API refused to delete some of them; the dialog stays open on those. */
  const [refused, setRefused] = useState<DeleteOutcome['refused']>([]);
  /** Selected CRM-provided fields left out of a bulk delete. */
  const [skipped, setSkipped] = useState(0);
  const soon = (what: string) => toast(`${what} isn't available in this CRM yet.`, 'info');

  /**
   * One object's fields in HubSpot's export columns (QA 29 Oct), with Used In and Fill rate
   * loaded for the export rather than taken from the table (which may still be loading). What
   * fails to load is a blank cell and is named in `missing`.
   */
  const exportSheetOf = async (
    key: string,
    properties: CustomPropertyDefinition[],
    missing: string[],
    file = `${key}-properties`,
  ): Promise<ExportSheet> => {
    const object = objects.find((o) => o.key === key);
    const name = object?.name ?? key;
    const [usages, fills] = await Promise.all([
      listPropertyUsage(key).then(usageMap, () => null),
      // Activities keep no fill rates.
      object?.activity
        ? new Map<string, number>()
        : listPropertyFillRates(key).then(fillMap, () => null),
    ]);
    if (!usages) missing.push(`Usages for ${name}`);
    if (!fills) missing.push(`Fill rate for ${name}`);
    return exportSheet({
      name,
      file,
      properties,
      groups: model?.groups[key] ?? [],
      members: new Map([...members].map(([id, m]) => [id, m.name || m.email])),
      usages,
      fills,
      access: accessLabel,
    });
  };
  const download = (f: ExportFile) => downloadFile(f.name, f.data, f.mime);
  const exportedToast = (sheets: ExportSheet[], missing: string[]) => {
    const n = sheets.reduce((sum, s) => sum + s.rows.length - 1, 0);
    const done = `Properties exported (${n} ${n === 1 ? 'property' : 'properties'})`;
    if (!missing.length) toast(done, 'success');
    else {
      toast(
        `${done}, but ${missing.join(', ')} could not be loaded: those cells are blank.`,
        'danger',
        {
          durationMs: null,
        },
      );
    }
  };
  /** The selected rows or one row's definition: a CSV of the open object's fields. */
  const exportDefs = async (list: Row[], file: string) => {
    const missing: string[] = [];
    const sheet = await exportSheetOf(
      objectKey,
      list.map((r) => r.p),
      missing,
      file,
    );
    download(exportFile([sheet], 'csv'));
    exportedToast([sheet], missing);
  };
  const [exportOpen, setExportOpen] = useState(false);
  /** The Export properties dialog: every field of the chosen objects, archived ones too. */
  const exportObjects = async (
    keys: string[],
    format: ExportFormat,
    progress: (done: number) => void,
  ) => {
    if (!model) return false;
    try {
      const missing: string[] = [];
      let done = 0;
      // A few objects at a time, so "Select all" doesn't send every object's requests at once.
      const sheets = await mapLimited(keys, 3, async (key) => {
        const list = [...(model.properties[key] ?? [])].sort(
          (a, b) => Number(a.archived) - Number(b.archived) || a.label.localeCompare(b.label),
        );
        const sheet = await exportSheetOf(key, list, missing);
        progress((done += 1));
        return sheet;
      });
      download(exportFile(sheets, format));
      exportedToast(sheets, missing);
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    }
  };
  const exportHistory = async (r: Row) => {
    try {
      const list = r.p.standard
        ? await listStandardPropertyHistory(objectKey, r.p.name)
        : await listPropertyHistory(r.p.id);
      const cell = (v: unknown) =>
        v === null || v === undefined ? '' : typeof v === 'string' ? v : JSON.stringify(v);
      downloadFile(
        `${r.p.name}-history.csv`,
        toCsv([
          ['Record ID', 'Old value', 'New value', 'Changed by', 'Source', 'Changed at'],
          ...list.map((h) => [
            h.objectId,
            cell(h.oldValue),
            cell(h.newValue),
            h.changedBy ? memberLabel(h.changedBy) : '',
            h.source,
            h.changedAt,
          ]),
        ]),
      );
      toast(
        list.length ? 'Property history downloaded' : 'This property has no history yet',
        'success',
      );
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };
  const archivable = (p: CustomPropertyDefinition) => !p.standard && !p.system;
  /**
   * Built-in, activity default and HubSpot fields: their access never changes. Our own
   * calculated fields (Events ROI…) are the business's, so theirs does.
   */
  const crmOwned = (p: CustomPropertyDefinition) =>
    Boolean(p.standard || p.system || p.crmProvided);
  /** Shows a change at once; the model reloads behind it (about 5 s). */
  const patchLocal = (ids: string[], change: Partial<CustomPropertyDefinition>) => {
    const set = new Set(ids);
    setModel((m) =>
      m
        ? {
            ...m,
            properties: {
              ...m.properties,
              [objectKey]: (m.properties[objectKey] ?? []).map((p) =>
                set.has(p.id) ? { ...p, ...change } : p,
              ),
            },
          }
        : m,
    );
  };
  /** Deleted fields leave the Archived tab at once, before the model reloads. */
  const dropLocal = (ids: string[]) => {
    const set = new Set(ids);
    setModel((m) =>
      m
        ? {
            ...m,
            properties: {
              ...m.properties,
              [objectKey]: (m.properties[objectKey] ?? []).filter((p) => !set.has(p.id)),
            },
          }
        : m,
    );
  };

  const rowMenu = (r: Row): MenuItem[] => [
    { label: 'Track changes', run: () => router.push(trackChangesHref(r.p)) },
    { label: 'Clone', run: () => openEditor('clone', r.p), disabled: !canManage },
    {
      label: 'Choose new property group',
      run: () => {
        setMoveTo(r.p.groupName ?? '');
        setMoving([r]);
      },
      disabled: !canManage,
    },
    // Users' changes are in the audit log (Track changes), not in property history.
    ...(object?.fieldOnly
      ? []
      : [
          {
            label: 'Export property history',
            run: () => void exportHistory(r),
            disabled: !superAdmin,
          },
        ]),
    {
      label: 'Export property definition',
      run: () => void exportDefs([r], `${r.p.name}-definition`),
    },
    {
      label: 'Manage access',
      run: () => openEditor('edit', r.p, 'access'),
      disabled: !canManage || crmOwned(r.p),
      title: crmOwned(r.p) ? "CRM properties' access can't be changed" : undefined,
    },
    {
      label: 'Archive',
      danger: true,
      run: () => setArchiving([r]),
      disabled: !canManage || !archivable(r.p),
      title: archivable(r.p) ? undefined : 'This property is provided by CRM and can’t be archived',
    },
  ];

  /* ------------------------------------------------------------- render */
  const sortTh = (key: SortKey, text: string) => {
    const on = sort.key === key;
    return (
      <th
        key={key}
        scope="col"
        aria-sort={on ? (sort.dir === 'asc' ? 'ascending' : 'descending') : 'none'}
        className={key === 'used' || key === 'fill' ? 'pp-num' : undefined}
      >
        <button
          type="button"
          className={cn('pp-sort', on && 'is-on')}
          onClick={() => setSort({ key, dir: on && sort.dir === 'asc' ? 'desc' : 'asc' })}
        >
          {text}
          <Ico name={on ? (sort.dir === 'asc' ? 'up' : 'down') : 'sort'} className="pp-sorti" />
        </button>
      </th>
    );
  };

  const from = Math.max(1, Math.min(current - 4, pages - 9));
  const nums = Array.from({ length: Math.min(pages, from + 9) - from + 1 }, (_, i) => from + i);

  const propsPanel = (
    <>
      <div className="pp-filters" role="group" aria-label="Filter properties">
        {FILTERS.map(([k, allLabel]) => (
          <button
            key={k}
            type="button"
            className={cn('pp-filter', f[k] && 'is-set')}
            aria-haspopup="listbox"
            aria-expanded="false"
            onClick={(e) => setPop({ kind: `filter:${k}`, anchor: e.currentTarget })}
          >
            {filterLabel(k, allLabel)}
            <Ico name="caret" className="pp-caret" />
          </button>
        ))}
        {anyFilter && (
          <button type="button" className="pp-textlink" onClick={() => setF(NO_FILTERS)}>
            Clear filters
          </button>
        )}
      </div>
      <div className="pp-toolbar">
        {!sel.size && (
          <label className="pp-search">
            <input
              type="search"
              placeholder="Search properties"
              aria-label="Search properties"
              value={q}
              onChange={(e) => {
                setQ(e.target.value);
                setPage(1);
              }}
            />
            <Ico name="search" />
          </label>
        )}
        {sel.size > 0 && (
          <div className="pp-bulk">
            <span>
              <b>{sel.size}</b> selected
            </span>
            <button
              type="button"
              className="pp-btn pp-btn--outline pp-btn--xs"
              disabled={!canManage}
              onClick={() => {
                setMoveTo('');
                setMoving(selected);
              }}
            >
              Add to group
            </button>
            <button
              type="button"
              className="pp-btn pp-btn--outline pp-btn--xs"
              disabled={!canManage}
              onClick={() => setArchiving(selected)}
            >
              Archive
            </button>
            <button
              type="button"
              className="pp-btn pp-btn--outline pp-btn--xs"
              disabled={!canManage}
              onClick={() => {
                setAccessTo('');
                // One property starts from who it is assigned to; several start empty.
                setAccessAssignees(assigneesOf(selected.length === 1 ? selected[0]!.p : null));
                setAccessOf(selected);
              }}
            >
              Manage access
            </button>
            <button
              type="button"
              className="pp-btn pp-btn--outline pp-btn--xs"
              onClick={() => void exportDefs(selected, `${objectKey}-properties-selected`)}
            >
              Export properties
            </button>
          </div>
        )}
        {DQ_OBJECTS.has(objectKey) && (
          <button
            type="button"
            className="pp-dqoff"
            title="Data quality monitoring isn't available in this CRM yet"
            onClick={() => soon('Data quality monitoring')}
          >
            <Ico name="lock" className="pp-i--sm" />
            Data quality monitoring is off
          </button>
        )}
        <button
          type="button"
          className="pp-btn pp-btn--primary"
          disabled={!canManage || !object}
          title={!canManage ? PROPERTY_SETTINGS_ONLY : undefined}
          onClick={() => setCreating(true)}
        >
          Create property
        </button>
      </div>
      <div className="pp-tablewrap">
        <table className="pp-table">
          <thead>
            <tr>
              <th className="pp-col-check">
                <input
                  type="checkbox"
                  className="pp-cb"
                  aria-label="Select all properties on this page"
                  checked={pageRows.length > 0 && pageRows.every((r) => sel.has(r.p.id))}
                  ref={(el) => {
                    if (el) {
                      el.indeterminate =
                        !pageRows.every((r) => sel.has(r.p.id)) &&
                        pageRows.some((r) => sel.has(r.p.id));
                    }
                  }}
                  onChange={(e) => pageRows.forEach((r) => toggleSel(r.p.id, e.target.checked))}
                />
              </th>
              {sortTh('label', 'Name')}
              {sortTh('access', 'Property Access')}
              {sortTh('group', 'Group')}
              {sortTh('by', 'Created by')}
              {sortTh('used', 'Used In')}
              {sortTh('fill', 'Fill Rate')}
            </tr>
          </thead>
          <tbody>
            {pageRows.map((r) => (
              <tr key={r.p.id} className={sel.has(r.p.id) ? 'is-sel' : undefined}>
                <td className="pp-col-check">
                  <input
                    type="checkbox"
                    className="pp-cb"
                    aria-label={`Select ${r.label}`}
                    checked={sel.has(r.p.id)}
                    onChange={(e) => toggleSel(r.p.id, e.target.checked)}
                  />
                </td>
                <td className="pp-namecell">
                  <div className="pp-name">
                    <div>
                      <button
                        type="button"
                        className="pp-name__link"
                        onClick={() => openEditor('edit', r.p)}
                      >
                        {r.label}
                      </button>
                      <span className="pp-name__type">{r.type}</span>
                    </div>
                    <button
                      type="button"
                      className="pp-more"
                      aria-haspopup="menu"
                      aria-expanded="false"
                      aria-label={`More actions for ${r.label}`}
                      onClick={(e) => setPop({ kind: 'more', anchor: e.currentTarget, row: r })}
                    >
                      More
                      <Ico name="caret" className="pp-caret" />
                    </button>
                  </div>
                </td>
                <td>
                  <button
                    type="button"
                    className="pp-access"
                    disabled={!canManage}
                    onClick={() => openEditor('edit', r.p, 'access')}
                  >
                    {r.access}
                  </button>
                </td>
                <td>{r.group}</td>
                <td title={r.creator.title}>{r.by}</td>
                <td className="pp-num">{r.used}</td>
                <td className="pp-num">{fillText(r.fill)}</td>
              </tr>
            ))}
          </tbody>
        </table>
        {filtered.length === 0 && (
          <div className="pp-empty">
            <p className="pp-empty__t">
              {model ? 'No properties match your search' : 'Loading properties…'}
            </p>
            {model && (
              <p>
                Try a different search term or{' '}
                <button
                  type="button"
                  className="pp-textlink"
                  onClick={() => {
                    setF(NO_FILTERS);
                    setQ('');
                  }}
                >
                  clear all filters
                </button>
                .
              </p>
            )}
          </div>
        )}
      </div>
      {filtered.length > 0 && (
        <nav className="pp-pager" aria-label="Pagination">
          <button
            type="button"
            className="pp-pager__nav"
            disabled={current <= 1}
            onClick={() => setPage(current - 1)}
          >
            <Ico name="chevL" />
            Prev
          </button>
          {nums.map((n) => (
            <button
              key={n}
              type="button"
              className={cn('pp-pager__n', n === current && 'is-on')}
              aria-current={n === current ? 'page' : undefined}
              aria-label={`Page ${n}`}
              onClick={() => setPage(n)}
            >
              {n}
            </button>
          ))}
          <button
            type="button"
            className="pp-pager__nav"
            disabled={current >= pages}
            onClick={() => setPage(current + 1)}
          >
            Next
            <Ico name="chevR" />
          </button>
          <button
            type="button"
            className="pp-pager__per"
            aria-haspopup="listbox"
            aria-expanded="false"
            onClick={(e) => setPop({ kind: 'per', anchor: e.currentTarget })}
          >
            {per} per page
            <Ico name="caret" className="pp-caret" />
          </button>
        </nav>
      )}
    </>
  );

  return (
    <div className="pp">
      <header className="pp-head">
        <h1>Properties</h1>
        <div className="pp-head__actions">
          {DQ_OBJECTS.has(objectKey) && (
            <>
              <button
                type="button"
                className="pp-link-btn pp-link-btn--dark"
                onClick={() => soon('Data Agent')}
              >
                <Ico name="agent" />
                Data Agent
              </button>
              <button
                type="button"
                className="pp-link-btn pp-link-btn--dark"
                onClick={() => soon('Data Quality')}
              >
                <Ico name="lock" />
                Data Quality
              </button>
            </>
          )}
          <button
            type="button"
            className="pp-btn pp-btn--outline pp-btn--sm"
            disabled={!model || !objects.length}
            onClick={() => setExportOpen(true)}
          >
            Export properties
          </button>
        </div>
      </header>
      <p className="pp-intro">
        Properties are used to collect and store information about your records in the CRM. For
        example, a contact might have properties like First Name or Lead Status.
      </p>

      {error && (
        <Alert tone="danger">
          Couldn&apos;t load properties: {error}{' '}
          <button type="button" className="pp-textlink" onClick={() => void reload()}>
            Try again
          </button>
        </Alert>
      )}
      {!canManage && (
        <Alert tone="warning">
          You can view properties, but changing them needs the Edit property settings permission.
        </Alert>
      )}
      {membersNotice && <Alert tone="warning">{membersNotice}</Alert>}

      <div className="pp-objcard">
        <span className="pp-objcard__label" id="ppObjL">
          Select an object:
        </span>
        <button
          type="button"
          className="pp-select"
          aria-haspopup="listbox"
          aria-expanded="false"
          aria-labelledby="ppObjL ppObjV"
          onClick={(e) => setPop({ kind: 'object', anchor: e.currentTarget })}
        >
          <span id="ppObjV">{object ? `${object.singular} properties` : 'Loading…'}</span>
          <Ico name="caret" className="pp-caret" />
        </button>
        {/* Batch P1: only for those Settings › Objects opens for (Manage settings). */}
        {object &&
          canOpenSettingsHref(me, '/settings/objects') &&
          (SETTINGS_OBJECTS.has(object.key) || object.definition) && (
            <Link
              className="pp-objcard__link"
              href={`/settings/objects?object=${encodeURIComponent(object.key)}`}
            >
              Go to {object.name} settings
            </Link>
          )}
      </div>

      <div className="pp-tabs pp-tabs--cards" role="tablist" aria-label="Properties">
        {(
          [
            ['props', `Properties (${live.length})`],
            ['logic', 'Conditional logic'],
            ['groups', 'Groups'],
            ['archived', `Archived (${archived.length})`],
          ] as Array<[Tab, string]>
        ).map(([t, text]) => (
          <button
            key={t}
            type="button"
            className={cn('pp-tab', tab === t && 'is-on')}
            role="tab"
            aria-selected={tab === t}
            tabIndex={tab === t ? 0 : -1}
            aria-controls="ppPanel"
            onClick={() => setTab(t)}
          >
            {text}
          </button>
        ))}
      </div>

      <div className="pp-panel" id="ppPanel" role="tabpanel">
        {tab === 'props' && propsPanel}
        {tab === 'logic' && object && model && (
          <LogicSection key={objectKey} object={object} model={model} canEdit={canManage} />
        )}
        {tab === 'groups' && model && (
          <PropertyGroupsTab
            objectType={objectKey}
            groups={model.groups[objectKey] ?? []}
            properties={all}
            canManage={canManage}
            onChanged={reload}
            onView={(group) => {
              setF({ ...NO_FILTERS, group });
              setQ('');
              setPage(1);
              setTab('props');
            }}
          />
        )}
        {tab === 'archived' && (
          <ArchivedPanel
            archived={archived}
            byName={byName}
            canManage={canManage}
            onRestore={setRestoring}
            canDelete={superAdmin}
            onDelete={(list, left = 0) => {
              setDeleting(list);
              setSkipped(left);
            }}
          />
        )}
      </div>

      {/* popovers */}
      {pop?.kind === 'object' && (
        <ListPop
          anchor={pop.anchor}
          items={objects.map((o) => ({ value: o.key, label: `${o.singular} properties` }))}
          current={objectKey}
          onPick={setObject}
          onClose={closePop}
        />
      )}
      {pop?.kind.startsWith('filter:') &&
        (() => {
          const k = pop.kind.slice(7) as keyof Filters;
          return (
            <ListPop
              anchor={pop.anchor}
              items={filterItems(k)}
              current={f[k]}
              search={k === 'group' || k === 'type' || k === 'user'}
              onPick={(v) => {
                setF((cur) => ({ ...cur, [k]: v }));
                setPage(1);
              }}
              onClose={closePop}
            />
          );
        })()}
      {pop?.kind === 'per' && (
        <ListPop
          anchor={pop.anchor}
          items={PER_PAGE.map((n) => ({ value: String(n), label: `${n} per page` }))}
          current={String(per)}
          search={false}
          width={160}
          onPick={(v) => {
            setPer(Number(v));
            setPage(1);
            try {
              localStorage.setItem(PER_KEY, v);
            } catch {
              /* not kept */
            }
          }}
          onClose={closePop}
        />
      )}
      {pop?.kind === 'more' && pop.row && (
        <MenuPop anchor={pop.anchor} items={rowMenu(pop.row)} onClose={closePop} />
      )}

      {/* dialogs */}
      {exportOpen && (
        <ExportPropertiesDialog
          objects={objects}
          initial={[objectKey]}
          onExport={exportObjects}
          onClose={() => setExportOpen(false)}
        />
      )}
      {moving && model && (
        <PpModal
          title={moving.length > 1 ? 'Add to group' : 'Choose new property group'}
          okLabel="Save"
          onClose={() => setMoving(null)}
          onOk={async () => {
            if (!moveTo) {
              toast('Choose a group', 'danger');
              return false;
            }
            try {
              for (const r of moving) {
                if (r.p.standard) await setStandardPropertyGroup(objectKey, r.p.name, moveTo);
                else await updateCustomProperty(r.p.id, { groupName: moveTo });
              }
              const to = groupLabel(model, objectKey, moveTo);
              toast(
                moving.length > 1
                  ? `${moving.length} properties moved to ${to}`
                  : `Property moved to ${to}`,
                'success',
              );
              setSel(new Set());
              patchLocal(
                moving.filter((r) => !r.p.standard).map((r) => r.p.id),
                { groupName: moveTo },
              );
              void reload();
            } catch (err) {
              toast(errorText(err), 'danger');
              return false;
            }
          }}
        >
          <p className="pp-p">
            {moving.length > 1 ? (
              `${moving.length} properties will move to the group you choose.`
            ) : (
              <>
                Move <strong>{moving[0]!.label}</strong> to another group.
              </>
            )}
          </p>
          <GroupPicker groups={liveGroups(model, objectKey)} value={moveTo} onChange={setMoveTo} />
        </PpModal>
      )}
      {accessOf && (
        <PpModal
          title="Manage access"
          okLabel="Save"
          onClose={() => setAccessOf(null)}
          onOk={async () => {
            if (!accessTo) {
              toast('Choose an access level', 'danger');
              return false;
            }
            if (accessTo === 'assigned' && !hasAssignees(accessAssignees)) {
              toast('Choose at least one user or team', 'danger');
              return false;
            }
            const editable = accessOf.filter((r) => !crmOwned(r.p));
            // One at a time, going on past a failure, so the result names each property.
            const done: string[] = [];
            const failed: Array<{ id: string; label: string; error: string }> = [];
            for (const r of editable) {
              try {
                await updateCustomProperty(r.p.id, accessBody(accessTo, accessAssignees));
                done.push(r.label);
              } catch (err) {
                failed.push({ id: r.p.id, label: r.label, error: errorText(err) });
              }
            }
            const result = bulkAccessSummary(done, failed, accessOf.length - editable.length);
            toast(result.text, result.tone, failed.length ? { durationMs: 10000 } : {});
            if (done.length) await reload();
            if (failed.length) {
              // The popup stays open on the ones that didn't change, to try again.
              setAccessOf(editable.filter((r) => failed.some((x) => x.id === r.p.id)));
              return false;
            }
            setSel(new Set());
          }}
        >
          <p className="pp-p">
            Customize the level of access users and teams have to{' '}
            {accessOf.length > 1 ? (
              `${accessOf.length} properties`
            ) : (
              <strong>{accessOf[0]!.label}</strong>
            )}
            .
          </p>
          <p className="pp-help">Super admins always see and edit them, whichever you choose.</p>
          <div className="pp-radios" role="radiogroup" aria-label="Property access">
            {accessChoices(
              publicEnv().NEXT_PUBLIC_ASSIGNED_ACCESS,
              accessOf.length === 1 ? accessOf[0]!.p.access : null,
            ).map((c) => (
              <label key={c.value} className="pp-radio">
                <input
                  type="radio"
                  name="ppacc"
                  value={c.value}
                  checked={accessTo === c.value}
                  onChange={() => setAccessTo(c.value)}
                />
                <span>{c.label}</span>
              </label>
            ))}
          </div>
          {accessTo === 'assigned' && (
            <AccessAssigneesField
              value={accessAssignees}
              onChange={setAccessAssignees}
              replacesOn={accessOf.filter((r) => !crmOwned(r.p)).length}
            />
          )}
        </PpModal>
      )}
      {archiving && (
        <PpModal
          title={
            archiving.length > 1
              ? `Archive ${archiving.length} properties?`
              : `Archive ${archiving[0]!.label}?`
          }
          okLabel="Archive"
          danger
          onClose={() => setArchiving(null)}
          onOk={async () => {
            const list = archiving.filter((r) => archivable(r.p));
            try {
              for (const r of list) await archiveCustomProperty(r.p.id);
              const skipped = archiving.length - list.length;
              toast(
                `${list.length > 1 ? `${list.length} properties` : (list[0]?.label ?? 'Nothing')} archived${
                  skipped
                    ? `; ${skipped} CRM ${skipped === 1 ? 'property' : 'properties'} can't be`
                    : ''
                }`,
                'success',
              );
              setSel(new Set());
              patchLocal(
                list.map((r) => r.p.id),
                { archived: true, archivedAt: new Date().toISOString() },
              );
              void reload();
            } catch (err) {
              toast(errorText(err), 'danger');
              return false;
            }
          }}
        >
          <p className="pp-p">
            Archived properties are hidden from records, forms, filters and reports.{' '}
            {archiving.length > 1 ? 'They' : 'It'} can be restored from the Archived tab. Archived
            custom properties are permanently deleted after 90 days.
          </p>
        </PpModal>
      )}
      {restoring && (
        <PpModal
          title={
            restoring.length > 1
              ? `Restore ${restoring.length} properties?`
              : `Restore ${restoring[0]!.label}?`
          }
          okLabel="Restore"
          onClose={() => setRestoring(null)}
          onOk={async () => {
            try {
              for (const p of restoring) await restoreCustomProperty(p.id);
              toast(
                restoring.length > 1
                  ? `${restoring.length} properties restored`
                  : `${restoring[0]!.label} restored`,
                'success',
              );
              patchLocal(
                restoring.map((p) => p.id),
                { archived: false, archivedAt: null },
              );
              void reload();
            } catch (err) {
              toast(errorText(err), 'danger');
              // HUB-717: a restore past a Data Model limit stops the loop; the ones before it are
              // live again, so the list is loaded again rather than left showing them archived.
              void reload();
              return false;
            }
          }}
        >
          <p className="pp-p">
            {restoring.length > 1 ? 'They go' : 'It goes'} back to the Properties tab with
            {restoring.length > 1 ? ' their' : ' its'} values.
          </p>
        </PpModal>
      )}
      {deleting && (
        <PpModal
          title={
            deleting.length > 1
              ? `Delete ${deleting.length} properties?`
              : `Delete ${deleting[0]!.label}?`
          }
          okLabel="Delete"
          danger
          onClose={() => {
            setDeleting(null);
            setRefused([]);
          }}
          onOk={async () => {
            setRefused([]);
            const out = await deleteArchived(deleting, deleteCustomProperty);
            if (out.deleted.length) {
              toast(
                out.deleted.length > 1
                  ? `${out.deleted.length} properties deleted`
                  : `${deleting.find((p) => p.id === out.deleted[0])!.label} deleted`,
                'success',
              );
              dropLocal(out.deleted);
              void reload();
            }
            if (!out.refused.length) return;
            setDeleting(deleting.filter((p) => !out.deleted.includes(p.id)));
            setRefused(out.refused);
            return false;
          }}
        >
          {refused.length > 0 && (
            <Alert tone="danger">
              {refused.length === 1 && deleting.length === 1 ? (
                refused[0]!.message
              ) : (
                <ul className="pp-reasons">
                  {refused.map((r) => (
                    <li key={r.id}>
                      <b>{r.label}</b>: {r.message}
                    </li>
                  ))}
                </ul>
              )}
            </Alert>
          )}
          {/* Several fields: named, since each one's values go too (a refusal names its own). */}
          {deleting.length > 1 && !refused.length && (
            <ul className="pp-reasons pp-p">
              {deleting.map((p) => (
                <li key={p.id}>{p.label}</li>
              ))}
            </ul>
          )}
          {skipped > 0 && !refused.length && (
            <p className="pp-p">
              {skipped === 1
                ? '1 CRM-provided property is skipped: it can’t be deleted.'
                : `${skipped} CRM-provided properties are skipped: they can’t be deleted.`}
            </p>
          )}
          <p className="pp-p">
            {deleting.length > 1
              ? 'The properties and their values are deleted.'
              : 'The property and its values are deleted.'}{' '}
            This can&apos;t be undone.
          </p>
        </PpModal>
      )}

      {/* create + the full-page editor */}
      {creating && object && model && (
        <CreatePropertyPanel
          object={object}
          model={model}
          onClose={() => setCreating(false)}
          onSaved={() => void reload()}
          onMore={(seed) => {
            setCreating(false);
            setEditor({ mode: 'create', property: null, seed });
          }}
        />
      )}
      {editor && object && model && (
        <PropertyEditor
          mode={editor.mode}
          object={object}
          property={editor.property}
          seed={editor.seed}
          model={model}
          startSection={editor.section}
          onSection={(s) => {
            if (editor.property) {
              syncUrl({
                extra: {
                  action: editor.mode,
                  property: editor.property.name,
                  tab: SECTION_PARAMS[s],
                },
              });
            }
          }}
          viewOnly={!canManage}
          viewOnlyText={PROPERTY_SETTINGS_ONLY}
          onClose={closeEditor}
          onSaved={() => void reload()}
        />
      )}
    </div>
  );
}

/** The Archived tab: search, custom / default filter, restore and delete (single or selected). */
function ArchivedPanel({
  archived,
  byName,
  canManage,
  canDelete,
  onRestore,
  onDelete,
}: {
  archived: CustomPropertyDefinition[];
  byName: (p: CustomPropertyDefinition) => string;
  canManage: boolean;
  /** Deleting for good: Super Admins only (HubSpot; the API refuses others). */
  canDelete: boolean;
  onRestore: (list: CustomPropertyDefinition[]) => void;
  /** `skipped`: selected CRM-provided fields left out. */
  onDelete: (list: CustomPropertyDefinition[], skipped?: number) => void;
}) {
  const { timeZone } = useUserPrefs();
  const [q, setQ] = useState('');
  const [kind, setKind] = useState('');
  const [sel, setSel] = useState<Set<string>>(new Set());
  const [pop, setPop] = useState<HTMLElement | null>(null);
  const [sort, setSort] = useState<{ key: 'label' | 'type' | 'updatedAt'; dir: 'asc' | 'desc' }>({
    key: 'updatedAt',
    dir: 'desc',
  });

  const [from, setFrom] = useState('');
  const [to, setTo] = useState('');
  /** Archived before archivedAt was kept: the last change stands in for it. */
  const archivedOn = (p: CustomPropertyDefinition) => p.archivedAt ?? p.updatedAt;
  const list = archived
    .filter((p) => {
      if (q.trim() && !p.label.toLowerCase().includes(q.trim().toLowerCase())) return false;
      if (kind === 'custom' && isCrmProvided(p)) return false;
      if (kind === 'default' && !isCrmProvided(p)) return false;
      if (from && archivedDay(archivedOn(p), timeZone) < from) return false;
      if (to && archivedDay(archivedOn(p), timeZone) > to) return false;
      return true;
    })
    .sort((a, b) => {
      const v = (p: CustomPropertyDefinition) =>
        sort.key === 'type' ? fieldTypeLabel(p) : sort.key === 'label' ? p.label : archivedOn(p);
      return (
        v(a).localeCompare(v(b), undefined, { sensitivity: 'base' }) * (sort.dir === 'asc' ? 1 : -1)
      );
    });
  const chosen = list.filter((p) => sel.has(p.id));
  const chosenDeletable = chosen.filter(isDeletable);

  const th = (key: 'label' | 'type' | 'updatedAt', text: string) => {
    const on = sort.key === key;
    return (
      <th scope="col" aria-sort={on ? (sort.dir === 'asc' ? 'ascending' : 'descending') : 'none'}>
        <button
          type="button"
          className={cn('pp-sort', on && 'is-on')}
          onClick={() => setSort({ key, dir: on && sort.dir === 'asc' ? 'desc' : 'asc' })}
        >
          {text}
          <Ico name={on ? (sort.dir === 'asc' ? 'up' : 'down') : 'sort'} className="pp-sorti" />
        </button>
      </th>
    );
  };

  return (
    <>
      <p className="pp-p pp-anote">
        Archived custom properties can be restored for 90 days. After 90 days, they will be
        permanently deleted. Archived default properties can be restored at any time.
      </p>
      <div className="pp-toolbar pp-toolbar--wrap">
        <label className="pp-search pp-search--sm">
          <input
            type="search"
            placeholder="Search"
            aria-label="Search archived properties"
            value={q}
            onChange={(e) => setQ(e.target.value)}
          />
          <Ico name="search" />
        </label>
        <button
          type="button"
          className={cn('pp-filter', kind && 'is-set')}
          aria-haspopup="listbox"
          aria-expanded="false"
          onClick={(e) => setPop(e.currentTarget)}
        >
          {kind === 'custom'
            ? 'Custom properties'
            : kind === 'default'
              ? 'Default properties'
              : 'All properties'}
          <Ico name="caret" className="pp-caret" />
        </button>
        <div className="pp-daterange" role="group" aria-label="Archive date">
          <span className="pp-label">Archive date:</span>
          <label className="pp-date">
            <input
              type="date"
              aria-label="Archived from"
              value={from}
              max={to || undefined}
              onChange={(e) => setFrom(e.target.value)}
            />
          </label>
          <span>to</span>
          <label className="pp-date">
            <input
              type="date"
              aria-label="Archived to"
              value={to}
              min={from || undefined}
              onChange={(e) => setTo(e.target.value)}
            />
          </label>
        </div>
        {chosen.length > 0 && (
          <span className="pp-bulk">
            <span>
              <b>{chosen.length}</b> selected
            </span>
            <button
              type="button"
              className="pp-btn pp-btn--outline pp-btn--xs"
              disabled={!canManage}
              onClick={() => onRestore(chosen)}
            >
              Restore
            </button>
            <button
              type="button"
              className="pp-btn pp-btn--outline pp-btn--xs pp-btn--dangertext"
              disabled={!canDelete || !chosenDeletable.length}
              title={
                chosenDeletable.length < chosen.length
                  ? 'CRM-provided properties can’t be deleted; only your own are'
                  : undefined
              }
              onClick={() => onDelete(chosenDeletable, chosen.length - chosenDeletable.length)}
            >
              Delete
            </button>
          </span>
        )}
      </div>
      <div className="pp-tablewrap">
        <table className="pp-table">
          <thead>
            <tr>
              <th className="pp-col-check">
                <input
                  type="checkbox"
                  className="pp-cb"
                  aria-label="Select all archived properties"
                  checked={list.length > 0 && list.every((p) => sel.has(p.id))}
                  onChange={(e) =>
                    setSel(e.target.checked ? new Set(list.map((p) => p.id)) : new Set())
                  }
                />
              </th>
              {th('label', 'Name')}
              <th scope="col">Created by</th>
              {th('type', 'Property Type')}
              {th('updatedAt', 'Time Archived')}
            </tr>
          </thead>
          <tbody>
            {list.map((p) => (
              <tr key={p.id}>
                <td className="pp-col-check">
                  <input
                    type="checkbox"
                    className="pp-cb"
                    aria-label={`Select ${p.label}`}
                    checked={sel.has(p.id)}
                    onChange={(e) =>
                      setSel((cur) => {
                        const next = new Set(cur);
                        if (e.target.checked) next.add(p.id);
                        else next.delete(p.id);
                        return next;
                      })
                    }
                  />
                </td>
                <td>
                  <div className="pp-grow">
                    <span className="pp-strong">{p.label}</span>
                    <span className="pp-rowacts pp-rowacts--hover">
                      <button
                        type="button"
                        className="pp-btn pp-btn--pill pp-btn--xs pp-btn--soft"
                        disabled={!canManage}
                        aria-label={`Restore ${p.label}`}
                        onClick={() => onRestore([p])}
                      >
                        Restore
                      </button>
                      {isDeletable(p) && (
                        <button
                          type="button"
                          className="pp-btn pp-btn--pill pp-btn--xs pp-btn--dangertext"
                          disabled={!canDelete}
                          aria-label={`Delete ${p.label}`}
                          onClick={() => onDelete([p])}
                        >
                          Delete
                        </button>
                      )}
                    </span>
                  </div>
                </td>
                <td>{byName(p)}</td>
                <td>{fieldTypeLabel(p)}</td>
                <td className="pp-nowrap">{archivedTimeText(archivedOn(p), timeZone)}</td>
              </tr>
            ))}
          </tbody>
        </table>
        {list.length === 0 && (
          <div className="pp-empty">
            <p>There are no properties to show.</p>
          </div>
        )}
      </div>
      {pop && (
        <ListPop
          anchor={pop}
          items={[
            { value: '', label: 'All properties' },
            { value: 'custom', label: 'Custom properties' },
            { value: 'default', label: 'Default properties' },
          ]}
          current={kind}
          search={false}
          width={220}
          onPick={setKind}
          onClose={() => setPop(null)}
        />
      )}
    </>
  );
}

/** "Choose new property group": the object's groups, searchable; Enter picks the first match. */
function GroupPicker({
  groups,
  value,
  onChange,
}: {
  groups: Array<{ id: string; name: string; label: string }>;
  value: string;
  onChange: (name: string) => void;
}) {
  const [q, setQ] = useState('');
  const shown = groups
    .filter((g) => !q.trim() || g.label.toLowerCase().includes(q.trim().toLowerCase()))
    .sort((a, b) => byLabel(a.label, b.label));
  return (
    <div className="pp-field">
      <span className="pp-label">Property group</span>
      <label className="pp-search pp-search--pop">
        <input
          type="search"
          placeholder="Search groups"
          aria-label="Search groups"
          autoFocus
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Enter' && shown[0]) {
              e.preventDefault();
              onChange(shown[0].name);
            }
          }}
        />
        <Ico name="search" />
      </label>
      <div
        className="pp-optlist"
        role="listbox"
        aria-label="Property groups"
        style={{ maxHeight: 240, overflowY: 'auto' }}
      >
        {shown.length ? (
          shown.map((g) => (
            <button
              key={g.id}
              type="button"
              className={cn('pp-opt', g.name === value && 'is-on')}
              role="option"
              aria-selected={g.name === value}
              onClick={() => onChange(g.name)}
            >
              <span>{g.label}</span>
            </button>
          ))
        ) : (
          <div className="pp-empty-s">No results</div>
        )}
      </div>
    </div>
  );
}
